mysql - 删除某些列中可能具有空值的特定行

标签 mysql sql database

这是我尝试在 MySQL 中执行的查询:

DELETE from Connection 
where
(sourceIp , destinationIp,
destinationPort,
sourceServerId,
destinationServerId,
sourceProcessId,
destinationProcessId) IN (Select 
    sourceIp,
        destinationIp,
        destinationPort,
        sourceServerId,
        destinationServerId,
        sourceProcessId,
        destinationProcessId
from
    (Select 
        sourceIp,
            destinationIp,
            destinationPort,
            sourceServerId,
            destinationServerId,
            sourceProcessId,
            destinationProcessId
    from
        Connection

    where
        sourceIp = '12.43.34.53'
        and destinationIp = '12.43.34.65'
        and destinationPort = '3306'
        and ((sourceServerId = '1'
        and destinationServerId = '2'
        and sourceProcessId = '1'
        and destinationProcessId = '2')
        or (sourceServerId IS NULL
        and destinationServerId = '2'
        and destinationProcessId = '2')
        or (sourceServerId = '1'
        and sourceProcessId = '1'
        and destinationServerId is NULL))) as C);

我正在执行多个选择,因为我无法在 from 子句中指定相同的目标表。执行上面的查询。我的 table 看起来像这样:

  1. 源IP、目标IP、目标端口、源服务器Id、目标服务器Id、源进程Id、目标进程Id “12.43.34.53”、“12.43.34.65”、“3306”、NULL、“2”、NULL、“2”
  2. 源IP、目标IP、目标端口、源服务器Id、目标服务器Id、源进程Id、目标进程Id '12.43.34.53'、'12.43.34.65'、'3306'、'1'、NULL、'1'、NULL
  3. 源IP、目标IP、目标端口、源服务器Id、目标服务器Id、源进程Id、目标进程Id “12.43.34.53”、“12.43.34.65”、“3306”、“1”、“2”、“1”、“2”

上面的查询仅删除最后一行(#3)。但是,如果在 IN 处剪切查询并将其余部分作为 Select 执行,我会得到所有 3 行。是因为带有空值的 IN 不起作用吗?有关如何修改此查询以使其删除所有 3 行的任何建议。 (所有 id 和 ip 以及目标端口一起使表中的行唯一)

最佳答案

哇,您不需要任何这些选择,并且如果这些字段中的任何一个返回 NULL,在此能力下使用 IN 不会为您提供您想要的结果。 ……你的问题出在你的WHERE语句上。

上面的清理工作可以简化为:

DELETE from Connection 
where
    sourceIp = '12.43.34.53'
    and destinationIp = '12.43.34.65'
    and destinationPort = '3306'
    and ((sourceServerId = '1'
    and destinationServerId = '2'
    and sourceProcessId = '1'
    and destinationProcessId = '2')
    or (sourceServerId IS NULL
    and destinationServerId = '2'
    and destinationProcessId = '2')
    or (sourceServerId = '1'
    and sourceProcessId = '1'
    and destinationServerId is NULL))
;

之所以没有删除正确的记录,是因为 WHERE 子句中条件的优先顺序。我不会尝试解决这个问题,因为您的帖子需要一些工作,例如示例数据和所需的结果,因为我确信会有更好的方法来编写您的查询。

关于mysql - 删除某些列中可能具有空值的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38536925/

相关文章:

mysql - SQL - 从没有列的计数总和中舍入小数

sql - 合并两个不同表的查询结果

sql - 如何在我的数据库中执行数据完整性规则?

c# - Linq-to-entities,一次查询得到结果+行数

java - 在没有 int 的情况下对数组进行双重索引

php - 由于 IN 子句,Mysql 查询变慢。任何可能的选择?

sql - 在 SQL 中保存顺序首选项

MySQL:从一列中选择包含值的多行

php - 在 mySQL 上设置用户帐户

php - Mysql 搜索表 w/php 并返回结果