[英]Using NOT IN with GROUP CONCAT in MYSQL
我在我的 mysql 查詢中使用“ GROUP_CONCAT ”函數和“ NOT IN ”語句。 但由於未知原因,它沒有返回正確的值:
這是我的查詢不起作用:
select firstname, lastname
from t_user
where (status_Id NOT IN(Select GROUP_CONCAT(id) from t_status where code = 'ACT'
or code = 'WACT'))
Returns 46 rows
這是我的查詢工作:
select firstname, lastname
from t_user
where (status_Id NOT IN(1,4))
Returns 397 rows
GROUP_CONCAT子查詢的結果
(Select GROUP_CONCAT(id) from t_status where code = 'ACT' or code = 'WACT') = 1,4.
似乎查詢只處理 GROUP_CONCAT 子查詢返回的第一項。
所以我不明白發生了什么以及為什么我在兩種情況下都沒有相同的結果。
提前致謝 蓋爾
在這種情況下,您不需要使用GROUP_CONCAT
函數,因為它返回一個字符串值。 和
1, 4
與1
和4
非常不同。
select firstname, lastname
from t_user
where status_Id NOT IN
( Select id
from t_status
where code = 'ACT' or code = 'WACT'
)
LEFT JOIN
查詢的更好方法是使用LEFT JOIN
,
SELECT a.firstname, a.lastname
FROM t_user a
LEFT JOIN t_status b
ON a.t_status = b.id AND
b.code IN ('ACT', 'WACT')
WHERE b.id IS NULL
當您的問題提出時,可以利用從 GROUP_CONCAT 生成的列表。 因此,通常,您可以使用 GROUP_CONCAT 中的列表,如下所示:
根據規范,您可以簡單地使用 FIND_IN_SET 而不是 NOT IN 通過子查詢過濾字段
select firstname, lastname
from t_user
where NOT FIND_IN_SET(status_Id,
(Select GROUP_CONCAT(id) from t_status where code = 'ACT' or code = 'WACT')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.