简体   繁体   English

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

[英]Using results of GROUP_CONCAT in another sql query

I need to use the results contained in a GROUP_CONCAT in another query but i can't work out how to do this as they are in a comma separated list. 我需要在另一个查询中使用GROUP_CONCAT中包含的结果,但是由于它们在逗号分隔的列表中,因此我无法解决如何执行此操作。

For example, if GROUP_CONCAT(sample) contained a,b,c,d,e,f I tried to do 例如,如果GROUP_CONCAT(sample)包含a,b,c,d,e,f,我尝试这样做

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

but i get a syntax error. 但我收到语法错误。

I can't use 我不能用

 WHERE `this` = GROUP_CONCAT(sample)

because that tries to match this to the comma separated list 因为尝试匹配this以逗号分隔列表

Is there a specific method to achieve this? 是否有实现此目的的特定方法?

Use FIND_IN_SET 使用FIND_IN_SET

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

Or You can use (if there is no special reason to use GROUP_CONCAT ) 或者您可以使用(如果没有特殊原因使用GROUP_CONCAT

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

if sample is the column of orders table 如果sampleorders表的列

You should just combine the two queries: 您应该只结合两个查询:

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

This query can be optimized. 可以优化此查询。 You can write: 你可以写:

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

This has to use a full table scan and cannot take advantage of an index. 这必须使用全表扫描,并且不能利用索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM