SQL LEFT加入单个表

时间:2014-06-12 15:52:47

标签: mysql sql join left-join

假设表:

MyTable
idPrimary     idPerson     idSchool
-----------------------------------
1             20            6
2             20            3
3             21            2
4             22            6
5             23            6
6             24            3
7             22            7

我想找到所有上过学但未上学2或3的人。这意味着从上表中,答案是学生22和23.学生20上学6但遗憾的是上学3,从而否定了这个学生。

根据问题38549中的矩阵,我想要LEFT JOIN WHERE B.Key为NULL。

(出于好奇,所谓的LEFT OUTER JOIN?)

主要公式是:

SELECT <SELECT_LIST> FROM TableA.A LEFT JOIN TableB.B ON A.Key = B.Key WHERE B.Key IS NULL;

表A将是:

SELECT * FROM `MyTable` WHERE `idSchool` = '6';

表B将是:

SELECT * FROM `MyTable` WHERE `idSchool` = '2' OR `idSchool` = '3';

结果表应为:

SELECT `idPerson` FROM SELECT * FROM `MyTable` WHERE `idSchool` = '6' LEFT JOIN SELECT * FROM `MyTable` WHERE `idSchool` = '2' OR `idSchool` = '3' ON `idSchool` = `idSchool` WHERE `idSchool` = NULL;

可悲的是MySQL Workbench给我一个错误:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

在LEFT JOIN附近,基本上SQL引擎不喜欢我的TableA。如果我在括号中包装TableA,那么我会得到一个别名错误。

发出此查询的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

执行LEFT JOIN,检查ON子句中不需要的学校,并检查WHERE子句中是否匹配: -

SELECT DISTINCT a.idPrimary, a.idPerson, a.idSchool
FROM MyTable a
LEFT OUTER JOIN MyTable b
ON a.idPerson = b.idPerson
AND b.idSchool IN (2,3)
WHERE a.idSchool = 6
AND b.idSchool IS NULL

答案 1 :(得分:0)

对表别名使用AS关键字:

SELECT <SELECT_LIST>
  FROM TableA AS A
LEFT JOIN TableB AS B ON A.Key = B.Key
 WHERE B.Key IS NULL;

答案 2 :(得分:0)

JOIN的语法看起来更像:

SELECT *
FROM someTable
LEFT JOIN ON someOtherTable ON (someTable.someColumn = someOtherTable.someOtherColumn)
WHERE
someTable.id = 1;

但是在你的情况下,我认为NOT EXISTS看起来更清楚:

SELECT t1.* 
FROM `MyTable` t1
WHERE t1.`idSchool` = '6'
AND NOT EXISTS (
        SELECT t2.idPerson 
        FROM MyTable t2 
        WHERE t2.idSchool IN (2,3) AND t2.idPerson = t1.idPerson);