在另一个sql查询中使用GROUP_CONCAT的结果

时间:2014-02-08 12:52:34

标签: mysql sql

我需要在另一个查询中使用GROUP_CONCAT中包含的结果,但我无法理解如何执行此操作,因为它们位于以逗号分隔的列表中。

例如,如果GROUP_CONCAT(样本)包含a,b,c,d,e,f我试图做

SELECT * FROM `orders` WHERE `this` IN GROUP_CONCAT(sample)

但我收到语法错误。

我无法使用

 WHERE `this` = GROUP_CONCAT(sample)

因为它尝试将this与逗号分隔列表匹配

有没有具体的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

使用FIND_IN_SET

SELECT * FROM `orders` WHERE FIND_IN_SET(`this`, GROUP_CONCAT(sample))

或者您可以使用(如果没有特殊原因使用GROUP_CONCAT

SELECT * FROM `orders` WHERE `this` IN (sample)

如果sampleorders

的列

答案 1 :(得分:0)

您应该只合并两个查询:

SELECT *
FROM `orders`
WHERE exists (select 1
              from <other query without aggregation> s
              where this = s.sample
             )

可以优化此查询。你可以写:

select *
from orders o
where find_in_set(o.this, sample) > 0;

这必须使用全表扫描,不能利用索引。