我有 2 个子查询
1:
(select group_concat(a.name)
from A a
where a.id = c.a_id) as name
2:
(select group_concat(a.name)
from A a
where a.id = b.a_id) as name
现在我需要在其上创建一个union
意味着我需要唯一的名称列表作为Name
最佳答案
您需要对union
执行group_concat()
:
(select group_concat(abc.name)
from ((select name from A a where a.id = c.a_id)
union
(select name from A a where a.id = b.a_id)
) abc
)
但是,唉,由于 MySQL 作用域规则,这行不通——你要深入两层。因此,一种解决方案是或
:
(select group_concat(abc.name)
from A a
where a.id = c.a_id or a.id = b.a_id)
) abc
遗憾的是,性能可能会很糟糕,因为或
通常会阻止索引的使用。
嗯。 。 。获得唯一性并仍然使用索引的一种方法可能是简单的串联:
concat_ws(',',
(select group_concat(abc.name)
from A a
where a.id = c.a_id
),
(select group_concat(abc.name)
from A a
where a.id = c.a_id and a.id <> b.a_id
)
)
这并不是 100% 万无一失(两个不同的 a.id
行可能具有相同的名称,从而导致重复)。但在很多情况下,这都可行,并且每个子查询都应该利用 id
匹配的索引。
关于Mysql创建group_concat联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36581389/