SQL语句练习.汇总篇

易错点: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显示内连接,只显示匹配到的数据,匹配不到的不保留。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值