gpt4 book ai didi

mysql - 如何在mysql中查找列不为空的次数?

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:56 26 4
gpt4 key购买 nike

我在 mysql 表中有一堆名称以“X_”开头的列(例如:X_N、X_Pad、X_Server 等)。现在,这些列可以为空。

我想找出以 'X_' 开头的列最不为 NULL。

最佳答案

COUNT(expr)

Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement.

以下查询将返回每列的非空计数:

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>`

关于mysql - 如何在mysql中查找列不为空的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14475488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com