Mysql WHERE X匹配Y和Z.

时间:2017-05-31 19:59:23

标签: mysql select join tags

我有3个表用于存储图像,标签和两者之间的链接。结构是这样的:

表 - 照片

pid     name
--------------
1       image1
2       image2
3       image3
4       image4

表格 - 标签

tagID   tagName
---------------
1       red
2       blue
3       yellow
4       green

表 - photo_tag_bridge

pid     tagID
-------------
1       1
2       1
3       1
1       2
1       3

我想创建一个SELECT语句,只检索来自'照片的行。匹配多个tagID' s。我目前已经尝试将image1与tagID 1和2

匹配
SELECT photos.pid
, photo_tag_bridge.pid, photo_tag_bridge.tagID
, tags.tagID 
FROM photos
, photo_tag_bridge
, tags 
where photos.pid = photo_tag_bridge.pid 
AND photo_tag_bridge.tagID = 1 
AND photo_tag_bridge.tagID = 2 
GROUP BY photos.pid

这并没有带回任何东西,似乎我可能需要使用INNER JOIN?

2 个答案:

答案 0 :(得分:1)

有两个明显的解决方案。一种是加入2个photo_tag_bridge实例(如果您实际使用此表中的任何数据,则加入两个标记实例):

SELECT photos.pid
FROM photos
, photo_tag_bridge ptb_a
, photo_tag_bridge ptb_b
WHERE photos.pid = ptb_a.pid 
AND photos.pid = ptb_b.pid 
AND ptb_a.tagID = 1 
AND ptb_b.tagID = 2 

或者你做一个将DISTINCT计数与所需匹配数匹配的聚合(这很容易匹配,例如,3个标签中的任意两个):

SELECT photos.pid
FROM photos
, photo_tag_bridge ptb
WHERE photos.pid = ptb_a.pid 
AND photos.pid = bptb_b.pid 
AND ptb.tagID IN (1,2) 
GROUP BY photos.pid
HAVING COUNT(DISTINCT ptb.tagID)=2;

答案 1 :(得分:0)

至于我的理解,你需要获得具有多个标签的照片ID。

 create table #photo(id int,name varchar(10))
 create table #phototag(pid int,tgid int)
 create table #tag(id int,name varchar(10))

 select p.id,p.name from #photo p inner join #phototag pt on pt.pid=p.id group by p.id,p.name having count(*)>1