获取mysql中没有数据或空值的表列

获取mysql中没有数据或空值的表列,mysql,sql,database,select,Mysql,Sql,Database,Select,我有一些表格,我从中获取数据进行分析。我需要一些变通方法来查找列中有空数据或空值的记录。困难的部分是我需要消除包含数据的记录列。请参阅下面的示例以获得良好的理解 +----+------+------+------+------+ | ID | col1 | col2 | col3 | col4 | +----+------+------+------+------+ | 1 | Val1 | Val2 | Val3 | NULL | | 2 | NULL | Val2 | NULL | V

我有一些表格,我从中获取数据进行分析。我需要一些变通方法来查找列中有空数据或空值的记录。困难的部分是我需要消除包含数据的记录列。请参阅下面的示例以获得良好的理解

+----+------+------+------+------+
| 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、Perl、Ruby、.NET等)将结果集拉入,那么这当然可以完成。不过,我很难看到如何在纯SQL中实现这一点,而不必把事情搞得一团糟。也许是pivot?不幸的是,我不能使用任何其他语言,如PHP或Python。我正在尝试使用MySQL解决问题,如果有@sniperdAre,你可以使用MySQL 8.0来使用窗口功能吗?它是5.6@BillKarwin。你能提供一个参考链接或一些东西来了解更多吗?谢谢