我有一张表:
id | name1 | name2 | name3
1 | asa | NULL | das
2 | NULL | NULL | asas
我想删除有两次或更多次NULL值的每一行(这里是id = 2的那一行) 我已经用一个小的PHP脚本做了那个,但我想知道是否可以用mysql查询完成
我是mysql的新手,所以我还没有尝试过任何东西!
答案 0 :(得分:4)
您需要使用带有多个过滤器的WHERE
子句,每个过滤检查的列是null
:
delete
from yourtable
where
(name1 is null and name2 is null) or
(name1 is null and name3 is null) or
(name2 is null and name3 is null) or
(name1 is null and name2 is null and name3 is null)
答案 1 :(得分:1)
delete from table where
(name1 is null AND name2 is null) OR
(name2 is null AND name3 is null) OR
(name1 is null AND name3 is null) OR
(name1 is null AND name2 is null AND name3 is null)
答案 2 :(得分:1)
您可以使用IS NULL
为每列获取布尔值(0或1),对这些结果求和并删除总和大于或等于2的行。
像这样:
delete from your_table
where ((name1 is null) + (name2 is null) + (name3 is null)) >= 2
答案 3 :(得分:0)
相关的,如果你需要删除所有列为null的行,你可以这样做。
该过程将删除所有列为null的行,忽略可能设置为ID的主列。
DELIMITER //
CREATE PROCEDURE DeleteRowsAllColNull(IN tbl VARCHAR(64))
BEGIN
SET @tbl = tbl;
SET SESSION group_concat_max_len = 1000000;
SELECT CONCAT('DELETE FROM `',@tbl,'` WHERE ',(REPLACE(group_concat(concat('`',COLUMN_NAME, '` is NULL')),',',' AND ')),';') FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = @tbl AND COLUMN_KEY NOT LIKE 'PRI' into @delete_all;
PREPARE delete_all FROM @delete_all;
EXECUTE delete_all;
DEALLOCATE PREPARE delete_all;
END //
DELIMITER ;
执行这样的程序。
CALL DeleteRowsAllColNull('your table');