我有以下查询:
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 表中没有一行中文文本
我希望获得有关 Peter 的所有信息,其中填充了德语文本,中文文本为 NULL,但我最终没有得到任何结果。知道我错过了什么吗?
额外信息:语言表包含三种语言:德语、中文和英语, future 可能会添加更多语言。如果可以以某种方式设置此查询,它会立即自动加载所有语言,那将是非常棒的
最佳答案
我认为您需要这样做并将 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)
关于MySQL 为 null 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50611592/