简体   繁体   English

使用IN语法的mysql帮助!

[英]Mysql syntax using IN help!

i have a pictures table : pictures(articleid,pictureurl) 我有一张图片表: pictures(articleid,pictureurl)

And an articles table : articles(id,title,category) 和articles表: articles(id,title,category)

So, briefly, every article has a picture, and i link pictures with article using articleid column. 因此,简要地说,每篇文章都有图片,我使用articleid列将图片与文章链接起来。 now i want to select 5 pictures of articles in politic category. 现在我想从politic类别中选择文章的5张图片。

i think that can be done using IN but i can't figure out how to do it. 我认为可以使用IN来完成,但我不知道该怎么做。

Note: Please only one query, because i can do it by selecting articles firstly then getting the pictures. 注意:请只查询一个,因为我可以通过先选择文章然后获取图片来做到这一点。

Thanks 谢谢

To get five pictures from articles in a category you could do this: 要从某个类别的文章中获取五张图片,您可以执行以下操作:

SELECT pictures.pictureurl
  FROM articles, pictures
 WHERE articles.id = pictures.articleid AND articles.category = 'politic'
 ORDER BY [your sort criteria]
 LIMIT 5;

You could consider rephrasing the question a bit. 您可以考虑改一下这个问题。

If you are looking for an IN query instead of a JOIN this is an alternative to Alex's query: 如果您要查找IN查询而不是JOIN这是Alex查询的替代方法:

SELECT pictureurl 
  FROM pictures 
  WHERE arcticleid IN (SELECT id FROM articles WHERE category='politic') 
  LIMIT 5

Rewritten for clarification (see comments): 为澄清起见进行了重写(请参阅评论):

If you like to keep your JOIN criteria separated from your SELECT criteria, you can write something like the below: 如果您希望将JOIN条件与SELECT条件分开,则可以编写如下内容:

SELECT pictureurl
FROM pictures
JOIN articles ON id = articleid
WHERE category LIKE 'politics'
ORDER BY RAND()
LIMIT 5

I find the intent slightly clear when it's written like that, and maybe it's just me, but I have encountered complex queries written in the SELECT * FROM a, b, c form that worked under MySQL 4 which choke MySQL 5, whereas the above format works fine with both. 我发现这样写的意图有点清晰,也许只是我,但是我遇到了在SELECT * FROM a, b, c形式下编写的复杂查询,该形式在MySQL 4下工作,这使MySQL 5感到窒息,而上述格式两者都可以正常工作。

Also, if you use uniform ID column names for conformity, and to avoid confusing yourself in more complex scenarios, you can use the USING clause instead. 另外,如果您使用统一的ID列名称来确保一致性,并避免在更复杂的场景中感到困惑,则可以改用USING子句。 So if articles ID column is also named articlesid, the JOIN could be written like so: 因此,如果articles ID列也命名为articlesid,则JOIN可以这样写:

SELECT pictureurl
FROM pictures
JOIN articles USING (articleid)
...

You don't really need to use IN for this. 您实际上不需要为此使用IN IN serves when you nest queries or when you have a known set of values to check against. 当您嵌套查询或要检查一组已知值时, IN服务。

To select 5 random images in the politics category: 要在politics类别中选择5张随机图像:

SELECT pictureurl FROM articles, pictures WHERE pictures.articleid = articles.id AND articles.category = 'politics' ORDER BY RAND() LIMIT 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM