如何删除mysql中colb值为非数字的所有行?

wwodge7n  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(255)

我想删除所有包含col2中非数字值的行。我不知道如何在sql中实现这一点。

Col1    Col2  Col3

word1   123    Code
word2   124    Code
word3   tttt   code

Drop  * row from db.Table 
where col2 Value is not numeric;

我希望table看起来像这样:

Col1    Col2  Col3

word1   123    Code
word2   124    Code
lzfw57am

lzfw57am1#

在ansi标准sql中,您可以非常接近以下内容:

delete from t
    where substring(col2, 1, 1) between '0' and '9';

大多数数据库都支持更精确的比较方法。例如,在sql server中,您可以执行以下操作:

delete from t
    where try_convert(int, col2) is null;

在oracle中:

delete from t
    where regexp_like(col2, '[^0-9]');

在mysql中:

delete from t
    where col2 regexp '[^0-9]';
lf5gs5x2

lf5gs5x22#

你不需要使用正则表达式,也不需要制作你的专栏 TEXT 数据类型可能导致各种存储和i/o问题。
只是使用

DELETE FROM t1 WHERE concat('',coalesce(col2,1) * 1) <> coalesce(col2,0) ;

==============================================================
sql小提琴
mysql 5.6初始架构设置:

CREATE TABLE t1( col1 varchar(50), col2 varchar(50), col3 varchar(50) );

INSERT INTO t1 (col1,col2,col3) 
SELECT 'word1','123','Code' UNION ALL
SELECT 'word2','124','Code' UNION ALL
SELECT 'word3','tttt','Code' UNION ALL
SELECT 'word4','5ttt','Code' UNION ALL
SELECT 'word5','ttt5','Code'
;

CREATE TABLE t1_before ( col1 varchar(50), col2 varchar(50), col3 varchar(50) );
INSERT INTO t1_before (col1, col2, col3)
SELECT *
FROM t1 ;

删除前:

SELECT * FROM t1_before 

|  col1 | col2 | col3 |
|-------|------|------|
| word1 |  123 | Code |
| word2 |  124 | Code |
| word3 | tttt | Code |
| word4 | 5ttt | Code |
| word5 | ttt5 | Code |

删除语句

DELETE FROM t1 WHERE concat('',coalesce(col2,1) * 1) <> coalesce(col2,0) ;

删除后:

SELECT * FROM t1 

|  col1 | col2 | col3 |
|-------|------|------|
| word1 |  123 | Code |
| word2 |  124 | Code |

编辑:我改变了主意 DELETE 对账单 NULL 中的值 Col2 .

ki1q1bka

ki1q1bka3#

你可以试着用 regexp 关键字
[^0-9]+ [^0-9]+ 将获取包含非数值的值。

delete from t
where col2 regexp '[^0-9]+';

sqlfiddle:http://sqlfiddle.com/#!9/3717d/1号

相关问题