我正在搜索一个SQL请求,该请求为我提供了一个从未填充的表中的所有列。
例如,在像这样的表中:
column 1 | column 2 | column 3 | column 4 | column 5 ---------+----------+----------+----------+--------- value | NULL | value | value | NULL NULL | NULL | value | value | NULL value | NULL | value | NULL | NULL value | NULL | value | value | NULL
请求将返回:
column 2, column 5
我创建了这个小PHP脚本来生成查询并打印结果:
$columns = $sql->select("SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='table_name'");
$query = "SELECT ";
foreach($columns as $column) {
$query .= "case when count(".$column[0].") = 0 then '".$column[0]."' end, ";
}
$query = substr($query, 0,-2);
$query .= " FROM table_name";
var_dump($sql->select($query));
答案 0 :(得分:3)
类似的东西:
select case when count(column1) = 0 then 'column 1' end,
case when count(column2) = 0 then 'column 2' end,
case when count(column3) = 0 then 'column 3' end,
case when count(column4) = 0 then 'column 4' end,
case when count(column5) = 0 then 'column 5' end
from tablename
即。计算列的所有值,如果找到0则返回列名。
答案 1 :(得分:3)
您可以通过执行以下操作来确定列是否不包含任何值:
select 'column2'
from table t
having max(column2) is null;
您可以使用union all
:
select 'column1'
from table t
having max(column1) is null
union all
select 'column2'
from table t
having max(column2) is null
. . .
这会返回多行的结果。
如果你想要一行:
select concat_ws(', ',
(case when max(column1) is null then 'column1' end),
(case when max(column2) is null then 'column2' end),
(case when max(column3) is null then 'column3' end),
(case when max(column4) is null then 'column4' end),
(case when max(column5) is null then 'column5' end)
)
from table t;