【问题标题】:Using NOT IN with GROUP CONCAT in MYSQL在 MYSQL 中使用 NOT IN 和 GROUP CONCAT
【发布时间】:2013-03-10 16:16:23
【问题描述】:

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

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

提前感谢盖尔

【问题讨论】:

    标签: mysql sql subquery group-concat


    【解决方案1】:

    根据您的问题,可以利用从 GROUP_CONCAT 生成的列表。因此,一般情况下,您可以使用 GROUP_CONCAT 中的列表,如下所示:

    根据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')
    );
    

    【讨论】:

      【解决方案2】:

      在这种情况下,您不需要使用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
      

      【讨论】:

      • '还有一个更好的方法'......嗯,这些天我不太确定。不存在是 PDQ! (虽然在纯粹的审美层面上,我完全同意)
      • @Strawberry 这就是我使用better 的原因,没有说best:D
      猜你喜欢
      • 2016-03-06
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多