我在 mysql 表中有一堆列,其名称以“X_”开头(例如:X_N、X_Pad、X_Server 等)。现在,这些列可以为空。
我想找出以'X_'开头的列最不为NULL。
返回 SELECT 语句检索的行中 expr 的非 NULL 值的计数。
以下查询将为每列返回非空计数:
SELECT
COUNT(*) AS Total,
COUNT(X_N) AS NNC_N,
COUNT(X_Pad) AS NNC_Pad
FROM table;
您可以使用此查询从表中获取匹配列的列表:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<database_name>'
AND TABLE_NAME = '<table_name>'
AND COLUMN_NAME LIKE 'x\_%';
-- Output:
-- X_N
-- X_Pad
-- X_Server
您可以使用此查询来构建查询:
SELECT CONCAT('SELECT ', GROUP_CONCAT('COUNT(`', COLUMN_NAME, '`) AS `NNC of ', COLUMN_NAME, '`'), ' FROM `', TABLE_NAME, '`')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<database_name>'
AND TABLE_NAME = '<table_name>'
AND COLUMN_NAME LIKE 'x\_%';
-- Output (added whitespace for readability):
-- SELECT
-- COUNT(`X_N`) AS `NNC of X_N`,
-- COUNT(`X_Pad`) AS `NNC of X_Pad`,
-- COUNT(`X_Server`) AS `NNC of X_Server`
-- FROM `<table_name>`
备用:
SELECT GROUP_CONCAT('SELECT \'', COLUMN_NAME, '\' AS `Col`, COUNT(`', COLUMN_NAME , '`) AS `NNC` FROM `', TABLE_NAME , '`' SEPARATOR ' UNION ALL ')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<database_name>'
AND TABLE_NAME = '<table_name>'
AND COLUMN_NAME LIKE 'x\_%';
-- Output (added whitespace for readability):
-- SELECT 'X_N' AS `Col`, COUNT(`X_N`) AS `NNC` FROM `<table_name>` UNION ALL
-- SELECT 'X_Pad' AS `Col`, COUNT(`X_Pad`) AS `NNC` FROM `<table_name>` UNION ALL
-- SELECT 'X_Server' AS `Col`, COUNT(`X_Server`) AS `NNC` FROM `<table_name>`
从 db.tbl 中选择计数(X_N)、计数(X_Pad)、计数(X_Server);
可以的。
如果你只需要一个方法来生成这个 SQL,你可以使用
SELECT CONCAT("select ", GROUP_CONCAT("count(",column_name, ")"), " from ", table_schema, '.', table_name)
FROM information_schema.columns
WHERE table_schema='db' AND table_name='tbl' AND column_name LIKE 'X\_%';
大概是这样的?(未经测试)
SELECT
(SELECT COUNT(id) FROM My_Table WHERE X_1 != NULL) as x1,
(SELECT COUNT(id) FROM My_Table WHERE X_2 != NULL) as x2,
(SELECT COUNT(id) FROM My_Table WHERE X_3 != NULL) as x3,
(SELECT COUNT(id) FROM My_Table WHERE X_4 != NULL) as x4;