SQL - 如果其中一行符合条件,则排除多行

时间:2014-11-26 18:30:56

标签: sql multiple-records

如果其中一行符合条件,如何排除多行?



<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>
&#13;
&#13;
&#13;

如果组中的一行有单词&#34; Kerlix,我尝试排除给定instruction_id的所有行。&#34;所需的输出是:

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

有几种方法可以做到这一点。这是使用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
)

答案 1 :(得分:3)

您可以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