2009-04-28 56 views
1

選擇行我認爲我堅持了這種特殊的情況:
在一對多的情況

這裏是我的表:

item_table:
ID |項
1:
2:乙
3:C

attr_table:
ATTR | ITEM_ID
1:
1:2
2:1
2:3
3:2
3:3
我想知道,如果它在技術上是可以檢索其相關的任何物品attr = 1和3.答案只能是'B'。 同樣,如果我要求一個與attr = 1和2相關的項目,我應該只會得到'A'。

事情是,attr_table可能有很多行,我只想做一個查詢。

這個問題聽起來很容易,我很難過,因爲無法回答。

我希望有人聰明可以給我一個手...

回答

2

的例子是SQLServer的書面但查詢應該在MySQL上班逢。

鍵是HAVING COUNT語句等於必須匹配的屬性數量。如果屬性應該是(1,2,5),你就必須改變計數3

DECLARE @item_table TABLE (ID INTEGER PRIMARY KEY, Item CHAR(1)) 
DECLARE @attr_table TABLE (Attr INTEGER, Item_ID INTEGER) 

INSERT INTO @item_table VALUES (1, 'A') 
INSERT INTO @item_table VALUES (2, 'B') 
INSERT INTO @item_table VALUES (3, 'C') 

INSERT INTO @attr_table VALUES (1, 1) 
INSERT INTO @attr_table VALUES (1, 2) 
INSERT INTO @attr_table VALUES (2, 1) 
INSERT INTO @attr_table VALUES (2, 3) 
INSERT INTO @attr_table VALUES (3, 2) 
INSERT INTO @attr_table VALUES (3, 3) 


SELECT Item 
FROM @item_table i 
    INNER JOIN @attr_table a ON a.Item_ID = i.ID 
WHERE a.Attr IN (1, 3) 
GROUP BY Item 
HAVING COUNT(a.Attr) = 2 
+0

是不是做一個內部連接就等於第二次選擇? – 2009-04-28 08:01:48

+0

這是脆弱的,使用`count =`,因爲它不會工作,除非確實有兩個attr行對應於具有指定attrs的項目。但更糟糕的是,如果有兩個attr行,item_id = 1和attr = 1,那麼它會失敗,因此它會帶回一個誤報,一個沒有attr = 3的項。它會增加一個組的成本。 – tpdi 2009-04-28 08:12:50

0
select distinct item_table.item from item_table, attr_table 
where item_table.id = attr_table.item_id 
and attr_table.attr = 1 and attr_table.attr = 3; 

基本上它匹配你所期望的,並與一噸的結束行 - 然後不同的關鍵字操作,所以你得到最小的唯一行集作爲你的最終結果。

(Interally,我希望它效率更高,但不打擾匹配行的完整列表)。

1
SELECT * From attr_table a, item_table i 
    where a.item_id = i.id 
    and a.attr = 1 
    and a.item_id in (select item_id from attr_table where attr = 3); 

做工作返回一行對項目B.

1
select * from item_table a 
where exists (select * from attr_table b 
       where b.item_id = a.id and b.attr = 1) 
and exists (select * from attr_table c 
      where c.item_id = a.id and c.attr = 3); 

注意這個查詢說,你的規範說什麼:讓我的所有行從item_table那裏從存在至少一個排attr_table有該行的ID和第一個attr指定其中至少有一行attr_table有該行的ID和指定的第二個attr。

0

這可能是太晚,但我會建議使用一對夫婦的加入,像這樣:

select i.item, b.item_id, c.item_id 
from item_table i 
join attr_table b on i.id=b.item_id and b.item_id=1 
join attr_table c on i.id=c.item_id and c.item_id=2 

這就是我要做的事。

相關問題