选择条目不为空的列名 [英] Select column names whose entries are not null

查看:60
本文介绍了选择条目不为空的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个表的那些列的列表,这些列中至少有一个非NULL数据条目.

I would like to have a list of those columns of a table that have at least one non-NULL data entries in them.

换句话说,我想获得以下返回至少一个条目的列名:

In other words, I would like to get the column names for which the following returns at least one entry:

SELECT DISTINCT column_name FROM table WHERE column_name IS NOT NULL

我尝试了以下操作:

SELECT column_name
FROM information_schema.columns
WHERE table_name = "table_name"
AND EXISTS (
    SELECT DISTINCT column_name FROM table_name WHERE column_name IS NOT NULL
)

但是这还会返回所有条目均为NULL的列名.

But this also returns the column names where all the entries are NULL.

那我怎么只获得那些非NULL条目的列呢?

So how do I get only those columns with non-NULL entries?

推荐答案

INFORMATION_SCHEMA.COLUMNS 列出包含要执行的SQL的字符串,然后从该字符串中准备一条语句并执行它.

我们希望构建的SQL如下所示:

The SQL we wish to build will look like:

  SELECT 'column_a'
  FROM   table_name
  WHERE `column_a` IS NOT NULL
  HAVING COUNT(*)
UNION ALL
  SELECT 'column_b'
  FROM   table_name
  WHERE `column_b` IS NOT NULL
  HAVING COUNT(*)
-- etc.

(可以省略WHERE子句,并用COUNT(*)代替COUNT(column),但是我认为可能对索引列的效率较低).

(One could omit the WHERE clause and substitute COUNT(*) for COUNT(column), but I think that might be less efficient on indexed columns).

可以使用以下方法完成此操作:

This can be done using the following:

SET group_concat_max_len = 4294967295;

SELECT GROUP_CONCAT(
 ' SELECT ',QUOTE(COLUMN_NAME),
 ' FROM   table_name',
 ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL',
 ' HAVING COUNT(*)'
SEPARATOR ' UNION ALL ')
INTO   @sql
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA = DATABASE()
   AND TABLE_NAME = 'table_name';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

sqlfiddle 上查看.

这篇关于选择条目不为空的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆