2009-09-01 35 views
0

我有兩個表:MySQL的選擇鏈接的行

表 「A」:

+----------+ 
| item_id | 
+----------+ 
| 10  | 
| 20  | 
| 30  | 
| 40  | 
+----------+ 

和表 「B」:

+----------+-------------+ 
| item_id | user_id | 
+----------+-------------+ 
| 10  | 1   | 
| 10  | 2   | 
| 20  | 1   | 
| 30  | 2   | 
+----------+-------------+ 

字段 「ITEM_ID」 是一種常見的場。

如果我希望選擇表A中存在用戶1和用戶2的所有行(但不是隻存在其中一個存在的行),那麼如何構建此查詢? (我期待在item_id爲10的結果中有一行)。

回答

4

嘗試這種情況:

SELECT a.item_id 
    FROM TABLE_A a 
    JOIN TABLE_B b ON b.item_id = a.item_id 
    WHERE b.user_id IN (1, 2) 
GROUP BY a.item_id 
    HAVING COUNT(*) = 2 
+0

如果表格很大,這會比多次連接表B的其他示例快或慢嗎? (提供的表有適當的索引) – Ian

0
select item_id from table_b where user_id = 1 
intersect 
select item_id from table_b where user_id = 2 
+0

是否存在INTERSECT在MySQL? –

2

另一種替代方法:

SELECT A.* 
FROM tableA A 
INNER JOIN tableB B1 ON B1.item_id = A.item_id AND B1.user_id = 1 
INNER JOIN tableB B2 ON B2.item_id = A.item_id AND B2.user_id = 2 

加入A至一個用戶的其他用戶B兩次,一次,一次。這是另一種說明從B到自身的自聯接的方式,以便與兩個用戶一起查找項目。

這不會超出兩個用戶(每個用戶需要額外的連接)。

0
SELECT a.item_id FROM a 
    INNER JOIN b x ON a.item_id = x.item_id 
    INNER JOIN b y ON x.item_id = y.item_id 
     AND x.user_id = 1 AND y.user_id = 2;