mysql - 同一列上的两个 where 条件

标签 mysql sql where-clause

如何在 MySQL 中实现此查询?

DELETE FROM design_adv  WHERE `id` 
NOT in ('s23_1359182369', 's23_1359187062', 's23_1359192556',
          's23_1358938356', 's6_1358663190') 
AND `id` NOT like 'c%';

我需要删除所有行,除非它们在上面给出的列表中或以字母“c”开头。

最佳答案

不确定您真正想做什么。但是根据您的查询,该表将删除 in 子句中的每个 ID accept 和 like 运算符中的 wildcard 。任何 ID 都以 c 开头。试试这个保留所有的,除了那些在 IN caluse 和 LIKE..

您的问题已经给出了正确的查询:

I need to delete all rows that are either in the list given above or other start with the letter 'c'.

在你的表中执行大量删除之前,最好你真的可以在 fiddle 中尝试一下。

DELETE FROM demo  WHERE `id` 
 in ('s23_1359182369', 's23_1359187062',
        's23_1359192556',
          's23_1358938356', 's6_1358663190') 
OR `id` like 'c%';

  • OP 更新了问题:

I need to delete all rows *UNLESS* they are either *in* the list given above or start with the letter 'c'. IF we use OR here, OP's query will be deleting all the rows because any ID that's not in the list can also starts with c. Any ID that's not starting with c can also be in the list.. In that case you will need to use AND.

DELETE FROM demo  WHERE `id` 
NOT in ('s23_1359182369', 's23_1359187062',
        's23_1359192556',
          's23_1358938356', 's6_1358663190') 
AND `id` NOT like 'c%';

为了让您更好地理解,我使用了简单的数据点:

表:

| NUM | ID |
------------
|   1 | s1 |
|   2 | s2 |
|   3 | s3 |
|   4 | c1 |
|   5 | g1 |
|   6 | f1 |
|   7 | c3 |
|   8 | c2 |
|   9 | j1 |
|  10 | t1 |

删除查询:

DELETE FROM demo2  WHERE `id` 
 not in ('s1', 's2', 's3')
AND `id` not like 'c%';

查询后的结果:

| NUM | ID |
------------
|   1 | s1 |
|   2 | s2 |
|   3 | s3 |
|   4 | c1 |
|   7 | c3 |
|   8 | c2 |

关于mysql - 同一列上的两个 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536814/

相关文章:

mysql - 如何获取mysql中两个字符串值之间的行

php - 是否有一个好的解决方案来使用数据库的 session 集保存处理程序来处理 session 不活动?

java - mysql同一行不同列引用。(ifnull检查)

php - 如何回显表的正确行数

sql - 如何在多个表中查找不同的用户

mysql WHERE XXX = ZZZ 和 XXX = YYY

php - "do something OR DIE()"在 PHP 中是如何工作的?

c# - JOINS 或多个查询

C# - 将第一列从文本文件插入数据库

MySQL逻辑where函数我认为