易错点:null值的判断!!
null值无法和确定的值做比较
表: Customer
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| referee_id | int |
+-------------+---------+
在 SQL 中,id 是该表的主键列。
该表的每一行表示一个客户的 id、姓名以及推荐他们的客户的 id。
题目:找出那些没有被 id = 2 的客户 推荐 的客户的姓名。以 任意顺序 返回结果表。
方法一:select name from customer where referee_id != 2 or referee_id is null;
方法二:性能最高效,避开null
select name from customer where id not in (select id from customer where referee_id = 2);
方法三:select name from customer where ifnull(referee_id,0) != 2;
注:ifnull有两个参数,例如:ifnull(x,0),若x不为null,则返回x的值,若x为null,则返回0
方法四:select name from customer where nullif('2',referee_id) is not null;
注:使用nullif(a,b)函数时第一个参数位置不能为null。a除数与b值相等,返回null,否则返回a。有多个参数,可以嵌套使用。
扩展知识:
join对表左右连接。
union上下连接,去除重复的行。
union all 上下连接,不会去除重复的行。
inner显示内连接,只显示匹配到的数据,匹配不到的不保留。