mysql - 获取mysql中没有数据或空值的表列
问题描述
我有一些表,我从中获取数据进行分析。我需要一些解决方法来查找列中包含空数据或空值的记录。困难的部分是我需要消除包含数据的记录列。请参阅下面的示例以更好地理解。
+----+------+------+------+------+
| ID | col1 | col2 | col3 | col4 |
+----+------+------+------+------+
| 1 | Val1 | Val2 | Val3 | NULL |
| 2 | NULL | Val2 | NULL | Val4 |
| 3 | Val1 | Val2 | Val3 | |
+----+------+------+------+------+
是否可以使用查询获得如下输出?
+------+------+------+
| 1 | 2 | 3 |
+------+------+------+
| col4 | col1 | col4 |
| | col3 | |
| | | |
+------+------+------+
解决方案
在 MySQL 5.6.37 上测试:
select
max(if(d.rownum=r.rownum and d.id=1,d.val,null)) as `1`,
max(if(d.rownum=r.rownum and d.id=2,d.val,null)) as `2`,
max(if(d.rownum=r.rownum and d.id=3,d.val,null)) as `3`
from (select 1 as rownum union select 2 union select 3 union select 4) as r
left join (
select t.id, t.val, @n:=if(t.id=@id,@n+1,1) as rownum, @id:=t.id
from (select @n:=0 as n, @id:=0 as id) as _init
cross join (
select id, 'col1' as val from mytable where col1 is null
union select id, 'col2' from mytable where col2 is null
union select id, 'col3' from mytable where col3 is null
union select id, 'col4' from mytable where col4 is null
order by id, val) as t) as d
on r.rownum = d.rownum
group by r.rownum;
输出:
+------+------+------+
| 1 | 2 | 3 |
+------+------+------+
| col4 | col1 | col4 |
| NULL | col3 | NULL |
| NULL | NULL | NULL |
| NULL | NULL | NULL |
+------+------+------+
推荐阅读
- python - 图片未加载到网页
- javascript - 向上缩放 y 轴,同时使用 D3.js 向下缩放 x 轴
- dart - 如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?
- python - ttk 图像按钮仅显示集合中最后一个项目的图像
- javascript - 为什么javascript在正则表达式上抛出错误
- react-native - 反应原生 GeoFencing geolib 库
- sql - Oracle 合同模块中的 Oracle“付款期限天数”列。(Oracle 电子商务套件 12.1.3 版)
- pandas - Matplot 删除两个单独的日期时间点之间的空格
- javascript - Angular JS 在 jquery 之后不起作用。执行加载函数
- google-chrome - 如何恢复 Chrome 从 VS Code 访问任何本地文件的权限?