[英]Select from two tables only that rows that satisfies multiple conditions in second table
有3张表:
是否可以仅选择具有 2 个或更多特定标签的帖子?
为了选择所有带有特定标签的帖子,我这样做
SELECT * FROM posts, tags WHERE posts.id=tags.id_post AND post_tags.id_tag=1
我试过这个查询,但它给了我 post_tags.id_tag=1 或 post_tags.id_tag=2 的帖子
SELECT * FROM posts, tags WHERE posts.id=post_tags.id_post AND post_tags.id_tag IN (1,2)
SELECT posts.*
FROM posts
JOIN tags ON posts.id = tags.id_post
WHERE tags.id IN(1, 2)
GROUP BY posts.id
HAVING COUNT(tags.id_post) >= 2
如果我理解正确的话——
SELECT postName,count(*) as times -- you can add fields or omit the count(*)
FROM
(select * from posts where id in (1,2) posts -- you can replace the whole line with `posts`. this way gives you more room for conditions
inner join
(select * from tags where id_post in (1,2)) tags -- same as @posts
on posts.id=tags.id_post
group by postName -- if you added some fieldNames at the first line - add them here too..
having times>=2
-- AND tags.id=1 -- you can specify more conditions here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.