Mysql 连接和多重连接条件
我有一张用户表Mysql 连接和多重连接条件,mysql,sql,symfony1,doctrine-1.2,Mysql,Sql,Symfony1,Doctrine 1.2,我有一张用户表 ID NAME 1 John 2 Mike 3 Jack 和具有属性和用户ID的表 USER ATTRIBUTE 1 1 1 2 2 4 我需要选择属性为1和2的所有用户,因此,在本例中,用户为1。属性可以多于两个 我试过了 SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user WHERE a.attribute = 1 AND a.a
ID NAME
1 John
2 Mike
3 Jack
和具有属性和用户ID的表
USER ATTRIBUTE
1 1
1 2
2 4
我需要选择属性为1和2的所有用户,因此,在本例中,用户为1。属性可以多于两个
我试过了
SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user
WHERE a.attribute = 1 AND a.attribute = 2
但是它当然不起作用。having子句可以与sum一起使用
SELECT u.id FROM user u
INNER JOIN attributes a ON u.id = a.user
group by u.id
having ( sum(case when attribute in (1,2) then 1 else 0 end) ) =2
您正在查找属性1和属性2存在的所有用户。解决这个问题的一种方法——顾名思义——是EXISTS子句:
select *
from users u
where exists
(
select *
from user_attributes ua
where ua.user = u.id
and ua.attribute = 1
)
and exists
(
select *
from user_attributes ua
where ua.user = u.id
and ua.attribute = 2
);
另一种方法是:找到具有这两个属性的所有用户ID,然后从users表中选择
select *
from users
where id in
(
select user
from user_attributes
where attribute in (1,2)
group by user
having count(*) = 2
);
如果属性中存在重复项,则必须用countdistinct属性替换count*
还有其他方法可以做到这一点。我认为上面提到的这两个问题相当直截了当。您需要使用IN和GROUP BY的组合。。。必须做到这一点。如果您只需要用户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和名称,只需将从上述查询派生的此记录集作为筛选器连接到users表:
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
你需要一个由……组成的小组。。。。拥有
SELECT u.name
FROM
users u
JOIN
attributes a
ON u.id = a.user
WHERE a.id IN (1,2)
GROUP BY u.name
HAVING COUNT(*) = 2
它是一个大查询,用户表是核心。如果我已经习惯了在别的地方吃饭呢?以X公里为单位显示所选用户area@poh实际上,当您键入注释时,我正在演示如何通过联接将该筛选器应用于主表。