使用IS NULL的MySQL LEFT JOIN返回空结果

时间:2018-10-20 10:43:51

标签: mysql

我正在尝试选择不在表中的行。

简而言之,有五个表studentclssecschstd_sch。在这里,我想从std_sch 中选择不在 sch中的行 但是带有 IS NULL LEFT JOIN 返回空结果。

cls-类列表

id  |   ttl
===========
1   |   One
2   |   Two

sec-部分列表

id  |   ttl
===========
1   |   A
2   |   B

sch-奖学金列表

id  |   ttl
===============
1   |   First
2   |   Second
3   |   Third

student

id  |   ttl |   cls |   sec
===========================
1   |   John|   1   |   1
2   |   Paul|   1   |   0

sdt_sch-分配给学生的奖学金列表

id  |   s_id|   sdt_sch
=======================
1   |   1   |   1

Mysql代码

SELECT
    student.id AS sid, 
    student.ttl AS stdt, 
    cls.ttl AS cls,
    sec.ttl AS sec, 
    GROUP_CONCAT(sch.ttl) AS sch 
FROM 
    student
JOIN
    cls ON cls.id=student.cls 
LEFT JOIN
    sec ON sec.id=student.sec
LEFT JOIN
    std_sch ON std_sch.s_id = student.id
LEFT JOIN 
    sch ON sch.id = std_sch.sch_id
WHERE
    cls.id = 1
AND
    std_sch.sch_id IS NULL
GROUP BY
    student.id 

预期结果应如下:因为表sch - 1中存在第一奖学金(sdt_sch)。但是我得到的关于这一行的结果为空

sid |   stdt|   cls |   sec|    sch
============================================
1   |   John|   One |   A   |   Second,Third
2   |   Paul|   One |   A   |   First,Second,Third

我已附加-也SQL Fiddle

1 个答案:

答案 0 :(得分:1)

下一个怎么样

SELECT
  student.id AS sid, 
  student.ttl AS stdt, 
  cls.ttl AS cls,
  sec.ttl AS sec, 
  GROUP_CONCAT(sch.ttl) AS sch 
FROM 
  student
inner JOIN
  cls ON cls.id=student.cls 
LEFT JOIN
  sec ON sec.id=student.sec
left JOIN
  std_sch ON std_sch.s_id = student.id 
Left JOIN 
  sch ON sch.id != std_sch.sch_id or std_sch.sch_id is null
WHERE
  cls.id = 1
GROUP BY student.id;

提琴:here

想法是找到未分配给学生的学者,因此在sch上进行左联接将起作用

Left JOIN 
  sch ON sch.id != std_sch.sch_id or std_sch.sch_id is null