找不到logiq mysql请求SELECT ... IN

时间:2013-05-02 19:46:13

标签: mysql request

我有一个包含2个字段的“Posts_Tags”表。

post_id  tag_id
1          1
1          4
1          9
2          1
2          4
2          7
3          2
3          4

表格“标签”有3种类型

tag_id    type       name
1         geoloc     Paris
2         geloc      Rome
3         geoloc     London
4         paint      Abby
5         paint      Martin
6         paint      Dupont
7         designer   Paulo
8         designer   Stefy
9         designer   Michel

我想将post_id链接到几个tags_id。

我已经提出了一个简单的请求,要求使用以下标记获取所有帖子ID:巴黎,罗马。

 $arrray_in = array(1, 2); //This array is generated and can contain all Tags Ids, this is example value, maybe can i 10 values or more...
SELECT * FROM posts_tags WHERE tag_id IN($array_in) GROUP BY post_id

我希望能够只使用以下标签获得post_id:Paris(geoloc)和Abby(paint)。这个请求没有给我很好的结果(返回post_id:1,2,3,我只想要post_id:1,2)

$arrray_in = array(1, 2); //This array is generated and can contain all Tags Ids, this is example value, maybe can i 10 values or more...
    SELECT * FROM posts_tags WHERE tag_id IN($array_in) GROUP BY post_id

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容获取仅包含这些标记的帖子:

SELECT pt.post_id
FROM posts_tags pt
WHERE pt.tag_id IN(1, 4) 
GROUP BY pt.post_id
having count(distinct pt.tag_id) =2;

请参阅SQL Fiddle with Demo

如果您想要返回有关帖子的更多详细信息,那么您可以使用:

select *
from posts_tags pt1
inner join tags t
  on pt1.tag_id = t.tag_id
  and t.tag_id in (1, 4)
where exists (SELECT pt.post_id
              FROM posts_tags pt
              WHERE pt.tag_id IN(1, 4) 
                and pt1.post_id = pt.post_id
              GROUP BY post_id
              having count(distinct pt.tag_id) =2);

请参阅SQL Fiddle with Demo