简体   繁体   English

Mysql WHERE X同时匹配Y和Z

[英]Mysql WHERE X matches both Y AND Z

I have 3 tables for storing images, tags and a link between the two. 我有3个表格,用于存储图像,标签和两者之间的链接。 The structure is like this: 结构是这样的:

Table - photos 表-照片

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

Table - tags 表-标签

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

Table - photo_tag_bridge 桌子-photo_tag_bridge

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

I want to create a SELECT statement to retrieve only the rows from 'photos' which match multiple 'tagID's. 我想创建一条SELECT语句,以仅从与多个“ tagID”匹配的“照片”中检索行。 I've currently got this to try and bring back just image1 as it matches tagID 1 and 2 我目前有这个尝试尝试带回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

This doesn't bring anything back and it seems i may need to use an INNER JOIN? 这不会带回任何东西,似乎我可能需要使用INNER JOIN?

There's 2 obvious solutions. 有2个明显的解决方案。 One is to join to 2 instances of photo_tag_bridge (and two instances of tags if you were actually using any data from this table ): 一种是加入2个photo_tag_bridge实例( 如果您实际上正在使用此表中的任何数据,则加入两个tag实例):

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 

Or you do an aggregate matching the DISTINCT count to the number of required matches (which is handy to match, for example, any 2 of 3 tags): 或者,您可以将DISTINCT计数与所需匹配数进行匹配(这很容易匹配,例如3个标记中的任意2个):

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;

As for my understanding, you need to get photo id which has multiple tags. 据我了解,您需要获取带有多个标签的带照片的身份证。

 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

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

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