Mysql

將 JOIN 添加到 GROUP_CONCAT()

  • January 2, 2017

我有一張主要是靜態目標的表格,還有一張用於跟踪使用者完成這些目標的情況。他們可以將完成與在另一個表格和/或文本註釋中輸入的一個或多個記錄相關聯。我想將所有這些一起格式化為一個條目,以便在表格中顯示(即每個目標一行)。

Completion這是一個可能看起來像的範例:

ID    userID    objectiveID    recordID    text
1     4         8              500         NULL
2     4         8              NULL        "Lorem ipsum..."
3     4         8              750         NULL

我已經做到了這一點:

SELECT objectiveID,
  GROUP_CONCAT(recordID SEPARATOR ',') AS records,
  GROUP_CONCAT(text SEPARATOR ',') AS text
FROM Completion AS c
GROUP BY objectiveID;

返回:

objectiveID    records    text
8              "500,750"  "Lorem ipsum..."

然而,我實際上想要顯示的是被引用的程式碼的一個屬性recordID……假設這是Record表格:

ID    userID    codeID
500   4         1111
750   4         2222

這是Code表格:

ID    description
1111  dolor
2222  sit amet

我想要的輸出是:

objectiveID    records            text
8              "dolor, sit amet"  "Lorem ipsum..."

合併其他值的最佳方法是什麼?

您將Completion(columns userID, recordID)加入 ( Recordcolumns userID, ID)

您將Record(column codeID)加入 ( Codecolumn ID)

這是建議的查詢

SELECT c.objectiveID,
  GROUP_CONCAT(d.description SEPARATOR ',') AS records,
  GROUP_CONCAT(c.text SEPARATOR ',') AS text
FROM Completion AS c
INNER JOIN Record AS r ON c.userID=r.userID AND c.recordID=r.ID
INNER JOIN Code   AS d ON r.codeID=d.ID
GROUP BY c.objectiveID;

由於GROUP_CONCAT 的預設分隔符是逗號,您可以重寫為

SELECT c.objectiveID,
  GROUP_CONCAT(d.description) AS records,
  GROUP_CONCAT(c.text) AS text
FROM Completion AS c
INNER JOIN Record AS r ON c.userID=r.userID AND c.recordID=r.ID
INNER JOIN Code   AS d ON r.codeID=d.ID
GROUP BY c.objectiveID;

引用自:https://dba.stackexchange.com/questions/159765