2013-07-08 74 views
2

我有3個表:冠軍,角色,champs_to_rolesWHERE子句需要多個值?

的champs_to_roles表看起來像這樣:

|ID_champ|ID_role| 
---------------- 
|  2|  2| 
|  4|  5| 
|  5|  3| 
|  3|  2| 
|  1|  1| 
|  1|  2| 

我想選擇的ID_champ WHERE ID_role = 1 AND ID_role = 2

在這一點上我有以下代碼:

SELECT DISTINCT `c`.`name` 
FROM `champions` AS c, 
(
    SELECT `ID_champ` 
    FROM `champs_to_roles` 
    WHERE `ID_role` IN(1,2) 
) AS r 
WHERE `r`.`ID_champ` = `c`.`ID` 

然而,這會返回ID_champ,ID_role = 1或Id_role = 2或者他們都是

如何獲取我需要的內容?

感謝很多:)

回答

4

使用兩個內連接到關聯表 - 每個角色類型:

SELECT c.name 
FROM champions c 
JOIN champs_to_roles ctr1 ON ctr1.ID_champ = c.id AND ctr1.ID_role = 1 
JOIN champs_to_roles ctr2 ON ctr2.ID_champ = c.id AND ctr2.ID_role = 2 

通過使用加入,排在champs_to_roles絕存在爲冠軍返回。

DISTINCT關鍵字用,因爲你不需要它

+0

感謝解決我的問題。如果我必須增加所需值的數量,您的解決方案非常靈活;) –

0

我可能會與解決方案去(除非你在你的關聯表,這似乎不太可能和一個不好的設計,如果甚至有可能有重複的條目)分配波希米亞,但出於完整性也有使用次數和檢查從子查詢

SELECT c.name 
FROM champions AS c 
INNER JOIN 
(
    SELECT ID_champ, COUNT(DISTINCT ID_role) AS NumRole 
    FROM champs_to_roles 
    WHERE ID_role IN(1,2) 
    GROUP BY ID_champ 
) AS r 
ON r.ID_champ = c.ID AND NumRole = 2 

返回角色的數量(這也可以沒有再選擇完成的可能性,但它是一個觸摸不易閱讀時你沒有返回你需要分組的列,等等)

+0

@Bohemian,@Kickstart,感謝您的回答。這工作很好。我發現自己這個解決方案: 'SELECT DISTINCT c.name FROM冠軍爲C, \t( SELECT ID_champ \t FROM champs_to_roles \t WHERE ID_role IN(1,2) GROUP BY ID_champ HAVING COUNT(*) = 2 \t)AS r WHERE r.ID_champ = c.ID' –

+0

這樣做,儘管我更喜歡使用當代連接語法。我使用了COUNT(DISTINCT ID_role),以防萬一ID_role對冠軍不是唯一的,但如果它是唯一的(即ID_champ和ID_role有唯一的覆蓋索引),則可以使用COUNT(*)。但我更喜歡@Bohemian提出的方法 – Kickstart

0

你可以嘗試這樣的:

Select 
    c.name 
from 
    champions c 
where 
    exists(select 
      1 
     from 
      champs_to_roles ctr1 
     where 
      ctr1.ID_champ = c.ID 
       and exists(select 
        1 
       from 
        champs_to_roles ctr2 
       where 
        ctr2.ID_champ = ctr1.ID_champ 
         and ctr2.ID_role <> ctr1.ID_role)) 
0

試試這個,

SELECT DISTINCT c.name 
FROM champions AS c, 
(
    SELECT c1.ID_champ 
    FROM champs_to_roles c1, champs_to_roles c2 
    WHERE c1.ID_role=1 and c2.ID_role=2 
    AND c1.ID_champ=c2.ID_champ 
) AS r 
WHERE r.ID_champ = c.ID