2014-09-23 88 views
0

我有用戶表加入和多和條件

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 

但當然不工作..

回答

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 
+0

這是大查詢和用戶表是「核心」。如果我已經在其他地方使用過'擁有'會怎麼樣? (顯示距選定區域X公里的用戶) – poh 2014-09-23 21:37:22

+0

@poh實際上,當您鍵入您的評論時,我正在展示如何通過連接將該過濾器應用於主表。 – 2014-09-23 21:38:22

+0

真棒,它的作品! – poh 2014-09-23 21:43:40

0

having子句可以和使用

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 
0

您正在尋找的人存在的所有用戶屬性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,然後從用戶表中選擇。

select * 
from users 
where id in 
(
    select user 
    from user_attributes 
    where attribute in (1,2) 
    group by user 
    having count(*) = 2 
); 

的情況下有在屬性重複條目,你將有count(distinct attribute)更換count(*)

還有其他方法可以解決這個問題。我認爲這兩個提到的是相當直接的。

0

你需要一個group by ....有

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