MySQL选择连接空值

时间:2017-04-16 10:19:12

标签: mysql join null

您好我正在尝试查询,它将显示每4个表中的4个值。

select i.name, c.name, s.name, d.name
from instructor i
join course c
    on i.pid = c.instructor
join course_taken ct
    on c.id = ct.cid
join student s
    on s.id = ct.sid
join department d
    on s.major = d.id or s.major is null
where i.name = 'lee';

除零空间外,一切都很好。

表格结构

--------------------------------------------------
| student | course  | instructor | department    |
--------------------------------------------------
| name   | name     | id         | id            |
--------------------------------------------------
| id     | id       | name       | name          |
--------------------------------------------------
| major  |instructor| department |               |
--------------------------------------------------

结果

--------------------------------------------------
| i.name    | c.name  | s.name  | d.name         |
--------------------------------------------------
| kim       | math    | jack    | cs             |
--------------------------------------------------
| kim       | math    | john    | cs             |  --> THIS VALUE IS
--------------------------------------------------
| kim       | math    | john    | ss             |  --> NULL AND SHOULD BE PRINTED IN NULL
--------------------------------------------------
| kim       |math     | json    | ss             |
--------------------------------------------------

如果“john”中的“cs”和“ss”为NULL,如何打印null?

1 个答案:

答案 0 :(得分:0)

USE COALESCE()功能如

select coalesce(i.name,'NULL') as iName, ...
from instructor i

根据您的评论,您似乎根本不想从name表格获得department列。在这种情况下,只需选择NULL,就像

一样
select i.name, c.name, s.name, null

(OR)

select i.name, c.name, s.name, 'null'