数据库如下:
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
);
我认为可以写得更好。(也许使用双连接?)
那么,如何优化(如果可以的话?)