简单的SQL JOIN查询

时间:2012-09-21 07:53:12

标签: sql join

即使是简单的JOIN查询,我仍然遇到困难。从我上一个问题Simple but nested SELECT query开始,我学到了很多东西,但仍无法完成JOIN次查询。 :(

我从last question获得此查询,并且正在运行:

SELECT c.value, d.value 
FROM a
LEFT JOIN b
    ON a.id = b.idy
LEFT JOIN c
    ON b.idx = c.id
LEFT JOIN d
    ON b.idx = d.id
WHERE a.name = "test" 

现在,我想在查询中添加另一个条件来查看表e,f,g,并且如果表a.id, b.idx, c.id, d.id中存在任何e,f,g },然后返回结果。例如,如果c.id上存在e.id,则应删除表c中的行。如果a.id上存在g.id,则不应继续,因为如果您从查询中取消a.id,则其他部分不应返回任何内容。

我已经建立了一个示例数据库结构,你可以在这里看到sql代码:Sample.sql

2 个答案:

答案 0 :(得分:2)

你的意思是这样的吗?

SELECT c.value, d.value 
FROM a
LEFT JOIN b
    ON a.id = b.idy
    AND b.id NOT IN (SELECT e.id FROM e UNION ALL SELECT f.id FROM f UNION ALL SELECT g.id FROM g)
LEFT JOIN c
    ON b.idx = c.id
    AND c.id NOT IN (SELECT e.id FROM e UNION ALL SELECT f.id FROM f UNION ALL SELECT g.id FROM g)
LEFT JOIN d
    ON b.idx = d.id
    AND d.id NOT IN (SELECT e.id FROM e UNION ALL SELECT f.id FROM f UNION ALL SELECT g.id FROM g)
WHERE a.name = "test" 
AND a.id NOT IN (SELECT e.id FROM e UNION ALL SELECT f.id FROM f UNION ALL SELECT g.id FROM g)

答案 1 :(得分:2)

不确定您的SQL方言,但使用MySQL可以使用:

AND NOT EXISTS(SELECT 1 FROM e WHERE e.idx = b.idx)