gpt4 book ai didi

mysql - 从表中仅选择具有空值/空值的列

转载 作者:行者123 更新时间:2023-11-29 00:26:51 26 4
gpt4 key购买 nike

我有一个看起来像这样的数据集,但列继续为 data4、data5 到 data20

id      data1       data2       data3
(int) (varchar) (int) (date)
-------------------------------------
1 xyz (null) 0000-00-00
2 (empty) 321 2013-09-02
3 abc 555 2013-02-29
4 def (null) 2013-09-02
5 lmn 678 2013-03-19

我只想选择包含空值或空值的列的行,以便客户可以决定哪些字段需要填写在他们的工单中。

data1       data2       data3
(varchar) (int) (date)
-------------------------------------
2 1,4 1,5

或者如果有人能想到更好的变体?我现在对任何事情都持开放态度,只要它在做我想要的工作。这可能吗?谢谢!

最佳答案

你可以像这样用动态 SQL 来做

DELIMITER $$
CREATE PROCEDURE sp_empty()
BEGIN
SET @sql = NULL;

SELECT GROUP_CONCAT(
CONCAT('(SELECT GROUP_CONCAT(id) FROM Table1 WHERE `',
column_name, '` IS NULL ',
CASE
WHEN data_type IN('varchar', 'char')
THEN CONCAT('OR `', column_name, '` = ''''')
WHEN data_type IN('date', 'datetime', 'time')
THEN CONCAT('OR `', column_name, '` = 0')
ELSE ''
END, ')`', column_name, '`'))
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = 'table1'
AND column_name NOT IN ('id')
GROUP BY table_name;

SET @sql = CONCAT('SELECT ', @sql);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

请注意,它会处理不同数据类型的列。

示例用法:

CALL sp_empty();

输出:

| DATA1 | DATA2 | DATA3 ||-------|-------|-------||     2 |   1,4 |     1 |

Here is SQLFiddle demo


You obviously don't necessarily have to use a stored procedure. It's just simplifies things on the calling end. You can do

SET @sql = NULL;

SELECT GROUP_CONCAT(
CONCAT('(SELECT GROUP_CONCAT(id) FROM Table1 WHERE `',
column_name, '` IS NULL ',
CASE
WHEN data_type IN('varchar', 'char')
THEN CONCAT('OR `', column_name, '` = ''''')
WHEN data_type IN('date', 'datetime', 'time')
THEN CONCAT('OR `', column_name, '` = 0')
ELSE ''
END, ')`', column_name, '`'))
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = 'table1'
AND column_name NOT IN ('id')
GROUP BY table_name;

SET @sql = CONCAT('SELECT ', @sql);

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

这是 SQLFiddle 演示


如果出于某种原因您不能使用带有动态 SQL 的版本,那么作为最后的手段,您可以自己生成这样的查询,包括您的所有列

SELECT 
(
SELECT GROUP_CONCAT(id)
FROM Table1
WHERE `data1` IS NULL
OR `data1` = ''
) `data1`,
(
SELECT GROUP_CONCAT(id)
FROM Table1
WHERE `data2` IS NULL
) `data2`,
(
SELECT GROUP_CONCAT(id)
FROM Table1
WHERE `data3` IS NULL
OR `data3` = 0
) `data3`
...

这是 SQLFiddle 演示

关于mysql - 从表中仅选择具有空值/空值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18521819/

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