我有用户表
ID NAME
1 John
2 Mike
3 Jack
以及包含属性和用户 ID 的表
USER ATTRIBUTE
1 1
1 2
2 4
我需要选择具有属性 1 AND 2 的所有用户(因此,在此示例中为用户 #1 John)。属性可以多于两个。
我试过了
SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user
WHERE a.attribute = 1 AND a.attribute = 2
但当然它不起作用..
最佳答案
您需要结合使用 IN()
和 GROUP BY ... HAVING
来实现此目的。如果您只需要用户 ID,也无需加入。所以类似:
SELECT user, COUNT(attribute) AS attribute_count
FROM attributes
WHERE attribute IN(...) /* include your set of attributes here */
GROUP BY user
HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */
如果您需要用户 ID 和名称,您只需将从上述查询派生的记录集作为过滤器加入到用户表中即可:
SELECT user.id, user.name
FROM user
INNER JOIN
(
SELECT user, COUNT(attribute) AS attribute_count
FROM attributes
WHERE attribute IN(...) /* include your set of attributes here */
GROUP BY user
HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */
) AS filter
ON user.id = filter.user
关于mysql - 连接和多重和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004866/