4

我在我的 mysql 查询中使用带有“ NOT IN ”语句的“ GROUP_CONCAT ”函数。但由于未知原因,它没有返回正确的值:

这是我的查询不起作用:

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 子查询返回的第一项。

所以我不明白发生了什么以及为什么我在两种情况下都没有相同的结果。

在此先感谢盖尔

4

2 回答 2

5

在这种情况下,您不需要使用GROUP_CONCAT函数,因为它返回一个字符串值。AND与and
1, 4非常不同。14

select  firstname, lastname
from    t_user
where   status_Id NOT IN 
        ( Select id 
          from t_status 
          where code = 'ACT' or code = 'WACT'
        )

纠正查询的更好方法是使用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
于 2013-03-21T08:40:16.663 回答
2

根据您的问题,可以利用从 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')
);
于 2019-04-17T12:50:02.373 回答