MySQL为null不返回任何内容

时间:2018-05-30 18:49:34

标签: mysql sql

我有以下查询:

select 
    emp.name, emp.birthdate, emp.ssn, emp.current_employee, 
    german.introduction as "German Intro", german.work_experience as "German Work Experience", german.education as "German Education",
    chinese.introduction as "Chinese Intro", chinese.work_experience as "Chinese Work Experience", chinese.education as "Chinese Education"
from employees emp
left join contact_info german on emp.id = german.id_employee
left join contact_info chinese on emp.id = chinese.id_employee
where emp.name like '%peter%' 
and (german.id_language = 1 or german.id_language IS NULL)
and (chinese.id_language = 2 or chinese.id_language IS NULL)

表的创建查询:

CREATE TABLE `contact_info` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_employee` int(11) NOT NULL,
  `id_language` int(11) NOT NULL,
  `introduction` text,
  `work_experience` text,
  `education` text,
  PRIMARY KEY (`id`)
) 
CREATE TABLE `employees` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `birthdate` date NOT NULL,
  `ssn` varchar(20) NOT NULL DEFAULT '',
  `current_employee` enum('Y','N') NOT NULL DEFAULT 'Y',
  PRIMARY KEY (`id`)
)
CREATE TABLE `languages` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `language_name` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) 

我在员工日志中有Peter的记录。我在contact_info表中有一行用德语文本,但我在contact_info表中没有中文文本的行

我希望得到关于彼得的所有信息,其中填充德语文本,中文名称为NULL,但最终没有结果。知道我错过了什么吗?

额外信息:语言表包含3种语言:德语,中文和英语,将来可能会添加更多语言。如果可以设置这个查询,它会自动加载所有语言,这将是非常棒的

2 个答案:

答案 0 :(得分:0)

我认为您需要这样做并将id_language添加到您的加入条件中。

select 
    emp.name, emp.birthdate, emp.ssn, emp.current_employee, 
    german.introduction as "German Intro", german.work_experience as "German Work Experience", german.education as "German Education",
    chinese.introduction as "Chinese Intro", chinese.work_experience as "Chinese Work Experience", chinese.education as "Chinese Education"
from employees emp
left join contact_info german on emp.id = german.id_employee AND german.id_language = 1
left join contact_info chinese on emp.id = chinese.id_employee AND chinese.id_language = 2
where emp.name like '%peter%' 
and (german.id_language = 1 or german.id_language IS NULL)
and (chinese.id_language = 2 or chinese.id_language IS NULL)

答案 1 :(得分:0)

当您使用left join时,条件应该(通常)进入on而不是where。所以:

select emp.name, emp.birthdate, emp.ssn, emp.current_employee, 
       german.introduction as "German Intro", german.work_experience as "German Work Experience", german.education as "German Education",
       chinese.introduction as "Chinese Intro", chinese.work_experience as "Chinese Work Experience", chinese.education as "Chinese Education"
from employees emp left join
     contact_info german 
     on emp.id = german.id_employee and german.id_language = 1 left join 
     contact_info chinese
     on emp.id = chinese.id_employee and chinese.id_language = 2
where emp.name like '%peter%' ;

where中包含条件是多余的。