如果其中一行满足条件,如何排除多行?
<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>
我正在尝试排除给定instruction_id的所有行,如果组中的一行具有"Kerlix"一词。 所需的输出将是:
<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>
有几种方法可以做到这一点。 这是一个使用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
)
- SQL 小提琴演示
你可以
做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
- SQL 小提琴演示