2

我有 3 张桌子:冠军、角色、champs_to_roles

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

4 回答 4

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 关键字被省略了,因为您不需要它(除非您的关联表中有重复的条目,这似乎不太可能并且即使可能也是糟糕的设计)

于 2013-07-08T08:45:21.317 回答
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
于 2013-07-08T09:08:34.290 回答
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))
于 2013-07-08T09:02:29.673 回答
0

我可能会选择 Bohemian 的解决方案,但为了完整起见,还可以使用计数并检查从子选择返回的角色数量

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

(这也可以在没有子选择的情况下完成,但是当您不返回需要分组的列等时,它的可读性会降低)

于 2013-07-08T08:54:38.690 回答