[英]MySQL: How to select where column A not in column B?
假設我有一個名為FRUITSALAD的表:
| ID | FRUIT | SALAD |
|----|--------|--------------|
| 1 | apple | apple,orange |
| 2 | orange | pear,banana |
| 3 | banana | apple |
| 4 | grape | apple,grape |
| 5 | pear | |
| 6 | | apple,pear |
注意:SALAD列包含任意數量的逗號分隔的水果。
如何在SALAD中沒有水果的情況下選擇ID? (第2、3、5行/第6行 )
我首先想到的是嘗試這種方法,但是它返回了存在水果的所有行:
SELECT id FROM fruitsalad WHERE fruit NOT IN (salad)
我希望在可能的情況下不使用聯接或嵌套子查詢來執行此操作,但我希望能將其完成。 提前致謝!
在MySQL中,您可以使用find_in_set()
進行此操作:
select id
from fruitsalad
where find_in_set(fruit, salad) = 0;
要處理第6行,您可能需要:
select id
from fruitsalad
where find_in_set(fruit, salad) = 0 and
fruit is not null and fruit <> '';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.