0

数据库如下:

Classes       Challenges         Class Challenges
id             id                  id
               title               class_id
                                   challenge_id

为了获得特定课程的所有挑战,我使用以下内容

SELECT 
    DISTINCT class_challenges.challenge_id, 
    challenges.title
FROM class_challenges 
LEFT JOIN challenges 
    ON class_challenges.challenge_id = challenges.id
WHERE class_challenges.class_id = :class_id
ORDER BY challenge_id

对于不属于特定类别的所有挑战,我该如何做同样的事情?到目前为止,我使用:

SELECT 
    DISTINCT challenges.id,
    challenges.title 
FROM 
    challenges,
    class_challenges
WHERE challenges.id NOT IN(
                            SELECT 
                                DISTINCT class_challenges.challenge_id
                            FROM class_challenges
                            LEFT JOIN challenges 
                                ON class_challenges.challenge_id = challenges.id
                            WHERE class_challenges.class_id = :class_id
                            ORDER BY challenge_id
                        );

我认为可以写得更好。(也许使用双连接?)

那么,如何优化(如果可以的话?)

4

3 回答 3

1

试试这个查询

SELECT
    t.id,
    t.title,
    t.CCID
FROM
(
    SELECT      
        challenges.id,
        challenges.title,
        class_challenges.id as CCID                 
    FROM 
        challenges
    LEFT JOIN class_challenges 
        ON class_challenges.challenge_id = challenges.id
) as t  
WHERE t.CCID IS NULL 
于 2012-12-30T18:18:11.297 回答
1

在没有看到您的预期结果的情况下,我的回答有点含糊,但无论如何这里有一个代码可以尝试。叫我视觉;)请在您尝试查询后发表评论。

代码列出了“每个班级的挑战”。您可以使用 avariable过滤掉特定class id.

SQLFIDDLE 演示

SELECT DISTINCT a.id, 
group_concat(b.challenge_id) as challengeIs,
group_concat(c.title) as Titles
FROM Classes a
LEFT JOIN 
class_challenges b
ON a.id = b.class_id
LEFT JOIN challenges c
ON b.challenge_id = c.id
group by a.id
ORDER BY a.id;

结果:

ID      CHALLENGEIS     TITLES
100     11,15       a,c
200     15          b
300     11,15       a,c
400     (null)      (null)
500     15          b

不属于特定类别的挑战

只是注意到我错过了添加这部分查询。

询问:

-- 不属于某个类别的挑战

SELECT DISTINCT c.id,
c.title, group_concat(a.id) as class
FROM challenges c
LEFT JOIN 
class_challenges b
ON b.challenge_id = c.id
LEFT JOIN Classes a
ON a.id = b.class_id
GROUP BY c.id
HAVING class is null
ORDER BY c.id;

结果:

ID  TITLE   CLASS
18  c   (null)
于 2012-12-30T15:39:41.767 回答
0

怎么样,使用反连接:

SELECT challenges.id, challenges.title
FROM challenges
LEFT JOIN class_challenges ON class_challenges.challenge_id = challenges.id
    AND class_challenges.class_id = :class_id
WHERE class_challenges.id IS NULL
于 2012-12-30T15:19:41.000 回答