0

我有一个包含 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

我希望能够仅获得带有以下标签 Paris (geoloc) 和 Abby (paint) 的 post_id。这个请求没有给我好的结果(返回 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
4

1 回答 1

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

于 2013-05-02T19:51:16.023 回答