簡體   English   中英

在另一個SQL查詢中使用GROUP_CONCAT的結果

[英]Using results of GROUP_CONCAT in another sql query

我需要在另一個查詢中使用GROUP_CONCAT中包含的結果,但是由於它們在逗號分隔的列表中,因此我無法解決如何執行此操作。

例如,如果GROUP_CONCAT(sample)包含a,b,c,d,e,f,我嘗試這樣做

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

但我收到語法錯誤。

我不能用

 WHERE `this` = GROUP_CONCAT(sample)

因為嘗試匹配this以逗號分隔列表

是否有實現此目的的特定方法?

使用FIND_IN_SET

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

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

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

如果sampleorders表的列

您應該只結合兩個查詢:

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;

這必須使用全表掃描,並且不能利用索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM