0

我的数据库有一个挑战表,其中包含以下列:Challenge_Name, Challenge_Description. 我有一个名为第二个表completed_challenges_junction,它有这些列:Member_Name, Challenge_Name. 我需要一种方法来显示挑战表中的所有挑战名称以及completed_challenges_junction. 如果没有匹配,那么我希望它显示NULL. 我想我已经非常接近让我的 SQL 代码工作了,这就是我现在所拥有的。

SELECT challenges.Challenge_Name, challenges.Challenge_Description, completed_challenges_junction.Member_Names 
FROM challenges 
LEFT JOIN completed_challenges_junction ON challenges.Challenge_Name=completed_challenges_junction.Challenge_Name

这可行,但也会带来另一个成员的重复条目。如果我使用WHERE Member_Name='testmember'它只在我需要它仍然显示所有Challenge_Names 时带来成员的条目。

4

3 回答 3

0

我不确定你到底想要什么,但也许你正在寻找 'group by' 子句和 group_concat 函数:

SELECT challenges.Challenge_Name, challenges.Challenge_Description,
    GROUP_CONCAT(completed_challenges_junction.Member_Names SEPARATOR ', ')
FROM challenges 
LEFT JOIN completed_challenges_junction
    ON challenges.Challenge_Name=completed_challenges_junction.Challenge_Name
GROUP BY challenges.Challenge_Name

此查询将返回每个 Challenge_Name 仅出现一次的结果。

于 2013-01-29T22:29:29.280 回答
0
SELECT
    A.Challenge_Name,A.Challenge_Description,
    GROUP_CONCAT(IFNULL(B.Member_Names,'')) Member_Names
FROM
    challenges A
    LEFT JOIN completed_challenges_junction B ON
    A.Challenge_Name=B.Challenge_Name AND
    A.Challenge_Description=B.Challenge_Description
GROUP BY
    A.Challenge_Name,A.Challenge_Description
;

或者

SELECT
    A.Challenge_Name,A.Challenge_Description,
    GROUP_CONCAT(IFNULL(B.Member_Names,'')) Member_Names
FROM
    challenges A
    LEFT JOIN completed_challenges_junction B
    USING (Challenge_Name,Challenge_Description)
GROUP BY
    A.Challenge_Name,A.Challenge_Description
;
于 2013-01-29T22:28:22.933 回答
0

您可以像这样将WHERE子句添加到ON条件中

SELECT challenges.Challenge_Name, challenges.Challenge_Description, completed_challenges_junction.Member_Names 
FROM challenges 
LEFT JOIN completed_challenges_junction ON (
  challenges.Challenge_Name=completed_challenges_junction.Challenge_Name
  AND Member_Name='testmember'
)

这样只有testmember条目会从 completed_challanges_junction 中出现,但会显示所有挑战。

于 2013-01-29T22:28:33.877 回答