簡體   English   中英

在兩個表上的GROUP_CONCAT

[英]GROUP_CONCAT on two tables

我有兩個表,它們具有獨立的ID(無法通過聯接進行連接),我想查詢並獲得兩列的GROUP_CONCAT。

示例:表“ a”的ID為: 1、2、3 表“ b”的ID為: 10、11

最終結果應為: 1、2、3、10、11

我嘗試了一些查詢:

SELECT CONCAT_WS(',', GROUP_CONCAT(a.id), GROUP_CONCAT(b.id)) AS combined FROM a, b

SELECT GROUP_CONCAT(a.id, b.id) AS combined FROM a, b

這些查詢雖然返回了8as,但仍返回了重復的結果,所有結果都來自a兩次,所有結果都來自b兩次

嘗試union all

select group_concat(ab.id) as ids
from ((select id from a
      ) union all
      (select id from b
      )
     ) ab;

您的查詢正在表之間進行交叉聯接,因此交叉聯接后的數據為:

a.id        b.id
 1           10
 1           11
 2           10
 2           11
 3           10
 3           11

union all后,數據為:

ab.id
  1
  2
  3
 10
 11

如果要復制,請使用union all 如果您不想重復,請使用union 無論哪種情況,您都需要如下查詢:

select group_concat(id) from
 (select id from a
  union
  select id from b) as ids;

以下查詢將生成您想要的。 您可以使用table_position動態列來確定哪個表在前。

 Select group_concat(id order by table_position) from 
   (
      select id, 1 as table_position from a
      union all
      select id, 2 as table_position from b
    )

暫無
暫無

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

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