在MYSQL中使用NOT IN和GROUP_CONCAT

问题描述 投票:3回答:2

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

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

先谢谢盖尔

mysql sql subquery group-concat
2个回答
3
投票

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

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

0
投票

根据specification,您可以简单地使用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')
);
© www.soinside.com 2019 - 2024. All rights reserved.