2012-08-11 58 views
1

我有表選擇在兩個用戶之間共同的所有項目從單個表

XYZ(存儲用戶和項目之間的關係)

| user_id | item_id | 
---------------------- 

一個項目可以屬於一個或多個用戶和反之亦然。

因此,鑑於USER_ID = AUSER_ID = B我該怎麼辦MySQL查詢選擇所有的項目屬於兩個用戶A和用戶B

+1

一些示例數據將是很好 – 2012-08-11 11:03:11

回答

4

試試這個:

SELECT Item_ID 
FROM xyz 
WHERE User_ID IN ('A','B') 
GROUP BY Item_ID 
HAVING COUNT(distinct user_id) = 2 

SQLFiddle Demo

+1

1'計數(不同ITEM_ID)= 2'會有點更安全 – Andomar 2012-08-11 11:03:49

+1

@Andomar:我認爲它應該是:'count(distinct user_id)= 2' – 2012-08-11 11:06:56

+0

@ypercube:我認爲你是對的:) – Andomar 2012-08-11 11:08:32

1
SELECT a.item_id 
FROM xyz AS a 
    JOIN xyz AS b 
    ON b.item_id = a.item_id 
WHERE a.user_id = 'A' 
    AND b.user_id = 'B' ; 

如果(user_id, item_id)組合不是唯一的,作出這樣的SELECT DISTINCT

1

另一種選擇:

select item_id from xyx 
where item_id IN(select item_id from xyz where user_id ='A') 
and item_id IN(select item_id from xyz where user_id ='B') 
1

這就夠了:http://sqlfiddle.com/#!2/63ad5/6

select item_id 
from xyz 
group by item_id 
having sum(user_id in ('A','B')) = 2 

ANSI SQL'y方式:

select item_id 
from xyz 
group by item_id 
having sum(case when user_id in ('A','B') then 1 end) = 2 
0

一種方法可以

SELECT temp1.item_id FROM ( SELECT DISTINCT ITEM_ID FROM pcadminlogging 其中userid = 'A' ) AS temp1中 JOIN( SELECT DISTINCT ITEM_ID FROM pcadminlogging 其中userid = 'B' ) AS TEMP2 ON temp1.item_id = temp2.​​item_id WHERE temp1.userid在( 'A', 'B')

相關問題