Mysql

將左連接的多行結果合併到一個唯一的單元格中

  • September 28, 2020

¡ 大家好!,我不知道如何創建一個新列,其中包含來自左連接的所有結果資訊(如果存在該值)

例子

表格1

--------------------------------------
| FieldID | FieldName | FieldAccount |
|------------------------------------|
|   01    |    Jon    |     12345    |
--------------------------------------

表 2

--------------------------------------
| FieldID | FieldName | FieldAccount |
|------------------------------------|
|   01    |    Jon    |     12345    |
|------------------------------------|
|   02    |  Charlie  |     12345    |
--------------------------------------

結果

From Table 1

-----------------------------------------------
| FieldID | FieldName | FieldAccount | LookAt |
|---------------------------------------------|
|   01    |    Jon    |    12345     |  01,02 |
-----------------------------------------------

欄位LookAt包含FieldAccount匹配的 ID

感謝和問候大家!

您可以為此使用子查詢和 GROUP_CONCAT

架構 (MySQL v8.0)

CREATE TABLE Table1 (
 `FieldID` INTEGER,
 `FieldName` VARCHAR(3),
 `FieldAccount` INTEGER
);

INSERT INTO Table1
 (`FieldID`, `FieldName`, `FieldAccount`)
VALUES
 ('01', 'Jon', '12345');

CREATE TABLE Table2 (
 `FieldID` INTEGER,
 `FieldName` VARCHAR(7),
 `FieldAccount` INTEGER
);

INSERT INTO Table2
 (`FieldID`, `FieldName`, `FieldAccount`)
VALUES
 ('01', 'Jon', '12345'),
 ('02', 'Charlie', '12345');

查詢 #1

SELECT
t1.*
,(SELECT GROUP_CONCAT(`FieldID`) FROM Table2 WHERE `FieldAccount` = t1.`FieldAccount`
) 'LookAt '
FROM Table1 t1;

| FieldID | FieldName | FieldAccount | LookAt  |
| ------- | --------- | ------------ | ------- |
| 1       | Jon       | 12345        | 1,2     |

在 DB Fiddle 上查看

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