简体   繁体   English

通过多个值过滤一对多关系

[英]Filter one-to-many relationship by multiple values

This has got to be a common thing, but I'm not having luck Googling around. 这一定是很平常的事情,但是我没有运气谷歌搜索。

I have a table of categories: 我有一个类别表:

Table A
catid | text
1     | Category A
2     | Category B
3     | Category C

This table is then joined to a map that keeps track of what categories a photo is in 然后将此表连接到一张地图,该地图可跟踪照片所在的类别

Table B
catid | photoid
1     | 1
2     | 1
1     | 2
3     | 3

What I need to do is filter the query so that I return only the photos that are in EVERY category selected. 我需要做的是过滤查询,以便仅返回选择的每个类别中的照片。 For example: 例如:

  1. If the user selects categories A and B, I return photo 1. 如果用户选择类别A和B,则返回照片1。
  2. If the user selects just category A, I return photos 1 and 2. 如果用户仅选择类别A,则返回照片1和2。
  3. If the user selects categories A,B and C - I return nothing. 如果用户选择类别A,B和C-我什么也不会返回。

Thanks for any help you can give. 谢谢你提供的所有帮助。

-Matt -Matt

One of the easiest ways to do it is: 最简单的方法之一是:

SELECT 
    * 
FROM 
    B 
WHERE 
    B.catid IN (1, 2) 
GROUP BY 
    B.photoid 
HAVING 
    COUNT(B.photoid) = 2

To match 3 categories you would do: 要匹配3个类别,您需要执行以下操作:

SELECT 
    * 
FROM 
    B 
WHERE 
    B.catid IN (1, 2, 3) 
GROUP BY 
    B.photoid 
HAVING 
    COUNT(B.photoid) = 3

You can also join the same table multiple times. 您也可以多次连接同一张表。 Or do a sub-query. 或执行子查询。 I would test a couple of different methods to see which executes most quickly for your dataset. 我将测试几种不同的方法,以查看哪种方法对您的数据集执行最快。

Use Not Exists subquery 使用不存在子查询

Select distinct photoid
From photoCategory pc
Where Not Exists 
    (Select * From category c
     Where catId <> pc.catId)

Answer is here... 答案在这里...

https://stackoverflow.com/a/17026879/520857 https://stackoverflow.com/a/17026879/520857

sorry for misleading answer just now 很抱歉刚才的误导性回答

And btw, what you're trying to do is called an INTERSECT, which MySQL doesn't inherently support thus the weird solution in the link. 顺便说一句,您要尝试的操作称为INTERSECT,MySQL本身并不支持INTERSECT,因此链接中的方法很奇怪。

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

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