MySQL 为 null 不返回任何内容

标签 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 表中没有一行中文文本

我希望获得有关 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/

相关文章:

PHP 显示从给定时间到特定事件的小时数

php - 仅将默认数字关联数组键更改为 "number",而不影响数组值

MySQL 按总和分组

mysql - 不同语言测验的数据库设计

sql - 将 SQL 中的选定值打印到文本框 VB6

php - 从某个阶段和级别获取分数列表

mysql - 像 mysql 一样将大型 csv 加载到 RDB 的推荐方法

java - 如何对 SQL 查询进行单元测试?

MySQL - 无法在查询中获得正确的排序依据和分组依据

mysql - 加入前 3 个兴趣领域以及每个用户行