子查询与加入

时间:2014-04-21 18:53:46

标签: mysql join

SELECT
    id
FROM
    Posts
WHERE
    subject_id = 1 
    OR subject_id IN (
        SELECT related_subject_id 
        FROM RelatedSubjects
        WHERE parent_subject_id = 1);

尝试选择当前主题的所有帖子,但也选择存储在另一个查找表中的任何子主题。以上查询有效,想知道如何使用连接

完成同样的事情

3 个答案:

答案 0 :(得分:0)

SELECT DISTINCT id
FROM Posts AS p
LEFT JOIN RelatedSubjects AS r 
ON p.subject_id = r.related_subject_id AND r.parent_subject_id = 1
WHERE p.subject_id = 1 OR r.related_subject_id IS NOT NULL

答案 1 :(得分:0)

假设索引正确,UNION通常比JOIN的{​​{1}}效果更好:

OR

答案 2 :(得分:0)

select
    `Posts`.`id`
From posts as `Posts`
LEFT join RelatedSubjects as `RelatedSubjects`
on (`RelatedSubjects`.`related_subject_id` = `Posts`.`subject_id`)
where `Posts`.`subject_id` = 1