【问题标题】:SQL - exclude multiple rows if one of the rows meets the conditionSQL - 如果其中一行满足条件,则排除多行
【发布时间】:2015-01-25 05:06:55
【问题描述】:

如果其中一行满足条件,如何排除多行?

<table>
  <th>Instruction_ID</th>
  <th>Instruction_Desc</th>
    <tr>
      <td>1</td>
      <td>Please use these products:</td>
    </tr>
      <tr>
      <td>1</td>
      <td>Kerlix</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Sodium Chloride</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Tegaderm</td>
    </tr>
    
    <tr>
      <td>2</td>
      <td>Please use these products</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Sodium Chloride</td>
    </tr>
</table>

如果组中的一行包含“Kerlix”一词,我将尝试排除给定指令 ID 的所有行。期望的输出是:

<table>
  <th>Instruction_ID</th>
  <th>Instruction_Desc</th>
    <tr>
      <td>2</td>
      <td>Please use these products</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Sodium Chloride</td>
    </tr>
</table>

【问题讨论】:

  • 你为什么一直编辑你的问题?您有 2 个已发布的解决方案都可以使用。

标签: sql multiple-records


【解决方案1】:

您可以使用self join 并使用left join

SELECT T1.Instruction_ID, T1.Comments
FROM Table1 T1
LEFT JOIN Table1 T2
ON T1.Instruction_Id = T2.Instruction_Id
and T2.Comments LIKE '%Kerlix%'
WHERE T2.Instruction_Id is NULL

【讨论】:

    【解决方案2】:

    有几种方法可以做到这一点。这是一个使用NOT IN的:

    SELECT *
    FROM Table1
    WHERE Instruction_ID NOT IN (
        SELECT Instruction_ID
        FROM Table1
        WHERE Comments LIKE '%Kerlix%'
    )
    

    还有一个使用NOT EXISTS:

    SELECT *
    FROM Table1 t1
    WHERE NOT EXISTS (
        SELECT 1
        FROM Table1 t2
        WHERE Comments LIKE '%Kerlix%' AND t1.Instruction_Id = t2.Instruction_Id
    )
    

    【讨论】:

    • 会SELECT distinct Instruction_ID 帮忙吗?
    • @Beth -- 嗯,怎么样?不确定我是否理解您的评论。在这种情况下,我认为没有任何理由增加 distinct 的额外开销。
    • 这就是我想知道的,如果添加 distinct 子句会提高性能。你说不会? distinct 所做的工作比连接重复值需要更长的时间?
    • @Beth -- 正确,在这种情况下,distinct 只会增加查询的开销。也许这就是你的想法:stackoverflow.com/questions/12201885/…
    猜你喜欢
    • 2021-06-06
    • 2015-10-13
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多