2016-07-23 28 views
0

這是我想在MySQL來執行查詢特定行:刪除可以有NULL值的一些列

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子句指定同一個目標表。上面的查詢執行。我的表看起來像這樣:

  1. SOURCEIP,destinationIp,destinationPort,sourceServerId,destinationServerId,sourceProcessId,destinationProcessId '12 .43.34.53' ,'12 .43.34.65' , '3306',NULL, '2',NULL, '2'
  2. SOURCEIP,destinationIp,destinationPort,sourceServerId,destinationServerId,sourceProcessId,destinationProcessId '12 .43.34.53' ,'12 .43.34.65' , '3306', '1',NULL, '1',NULL
  3. sourceIp,destinationIp,destinationPort,sourceServerId,destinationServerId,sourceProcessId,destinationProcessId '12 .43.34.53','12 .43.34.65','3306','1','2','1','2 '

以上查詢只刪除最後一行(#3)。但是,如果在IN中刪除查詢並將其餘部分執行爲Select,那麼我會得到所有3行。是否因爲帶有空值的IN不起作用?有關如何修改此查詢以使其刪除所有3行的任何建議。 (所有的IDS和IPS,目的端口一起使表中的行是唯一的)

回答

1

哇,你不需要任何的選擇,並且在這方面的能力使用IN不會給你想要的,如果任何結果這些字段返回NULL ..........您的問題與您的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子句條件中的優先順序的。我不打算試圖解開這個,因爲你的文章需要一些工作,如示例數據和期望的結果,因爲我確信會有更好的方式來編寫你的查詢。

相關問題