sql,hql等join条件字段为null时,易出现错误以及解决办法

1.null=null不成立,null<>null也不成立

2.

运行汇总当字段为null时,出现bug,及解决思路
join的字段为null,不会出现p1.id=p2.id
mysql> select * from yunxing_huizong;
+------+------+------+
| id   | cost | year |
+------+------+------+
| 1    |    1 | 2016 |
| 1    |    2 | 2017 |
| NULL |    2 | 2016 |
| NULL |    3 | 2017 |
+------+------+------+
=============================================
汇总
mysql> select id,sum(cost),year from(select p2.id,p2.cost,p1.year from 
(select * from yunxing_huizong)p1 left join 
(select * from yunxing_huizong)p2 on p1.id=p2.id and p1.year>=p2.year)p group by id,year;
+------+-----------+------+
| id   | sum(cost) | year |
+------+-----------+------+
| NULL | NULL      | 2016 |
| NULL | NULL      | 2017 |
| 1    | 1         | 2016 |
| 1    | 3         | 2017 |
+------+-----------+------+
===============================================
修改bug思路
将id为null的手动赋值为0或unknown,求出最终结果之后,再将id为0或unknown的改为null,即可
mysql> select case when id is NULL then 0 else id end as id,cost,year from yunxing_huizong; 
+----+------+------+
| id | cost | year |
+----+------+------+
| 1  |    1 | 2016 |
| 1  |    2 | 2017 |
| 0  |    2 | 2016 |
| 0  |    3 | 2017 |
+----+------+------+


mysql> select id,sum(cost),year from 
(select p2.id,p2.cost,p1.year from 
(select case when id is NULL then "unkow" else id end as id,cost,year from yunxing_huizong)p1 left join 
(select case when id is NULL then "unkow" else id end as id,cost,year from yunxing_huizong)p2 on p1.id=p2.id and p1.year>=p2.year)p group by id,year;
+-------+-----------+------+
| id    | sum(cost) | year |
+-------+-----------+------+
| 1     | 1         | 2016 |
| 1     | 3         | 2017 |
| unkow | 2         | 2016 |
| unkow | 5         | 2017 |
+-------+-----------+------+
得到正确结果
mysql> select case when id="unkow" then null else id end as id,`sum(cost)` sum_cost,year from (select id,sum(cost),year from (select p2.id,p2.cost,p1.year from (select case when id is NULL then "unkow" else id end as id,cost,year from yunxing_huizong)p1 left join (select case when id is NULL then "unkow" else id end as id,cost,year from yunxing_huizong)p2 on p1.id=p2.id and p1.year>=p2.year)p group by id,year)pp;
+------+----------+------+
| id   | sum_cost | year |
+------+----------+------+
| 1    | 1        | 2016 |
| 1    | 3        | 2017 |
| NULL | 2        | 2016 |
| NULL | 5        | 2017 |
+------+----------+------+

猜你喜欢

转载自blog.csdn.net/kaaosidao/article/details/78563904