通过外键将值列表放到一列中

xyhw6mcr  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(275)

我有两个表“sample”和“processes”,我想在一列中得到给定sample的所有进程。
表“示例”示例:

----------------------------------------
|           Sample Table               |
|                                      |
|id  | timestamp  | other columns...   |
 --------------------------------------
|1   | 24/04/1994 | ...                |
|2   | 25/04/1994 | ...                |
|... |...         | ....               |  
----------------------------------------

表“过程”示例:

----------------------------------------
|          Processes Table             |
|                                      |
|id  | sample_id  | process_name       |
 --------------------------------------
|1   | 1          | facebook           |
|2   | 1          | tinder             |
|3   | 1          | clash royale       |
|4   | 2          | uno                |
|5   | 2          | whatsapp           |
|... |...         | ....               |  
----------------------------------------

结果:

------------------------------------------------------------
|          Result Table                                     |
|                                                           |
|sample_id  | timestamp  | processes                        |
 -----------------------------------------------------------
|1          | 24/04/1994 | [facebook, tinder, clash royale] |
|2          | 25/04/1994 | [uno, whatsapp]                  |
------------------------------------------------------------

是否可以通过sql查询来实现这一点?怎样?
p、 s:我知道我可以通过以下方法获得给定样本的所有过程:

SELECT sample_id, timestamp, process_name
FROM sample, processes
WHERE sample.id = processes.sample_id

但这给了我太多不必要的争吵

6rvt4ljy

6rvt4ljy1#

你可以试着用 GROUP_CONCATCONCAT 功能。
架构(mysql v5.7)

CREATE TABLE sample(
   id INT,
   timestamp DATE

);

INSERT INTO sample VALUES (1,'1994/04/24'); 
INSERT INTO sample VALUES (2,'1994/04/25'); 

CREATE TABLE processes(
   id INT,
   sample_id INT,
  process_name VARCHAR(50)

);

INSERT INTO processes VALUES (1   ,1,'facebook');
INSERT INTO processes VALUES (2   ,1,'tinder');
INSERT INTO processes VALUES (3   ,1,'clash');
INSERT INTO processes VALUES (4   ,2,'uno');
INSERT INTO processes VALUES (5   ,2,'whatsapp');

查询#1

SELECT sample_id, timestamp, CONCAT('[',GROUP_CONCAT(process_name),']') processes
FROM sample JOIN processes ON sample.id = processes.sample_id
GROUP BY sample_id, timestamp;

| sample_id | timestamp  | processes               |
| --------- | ---------- | ----------------------- |
| 1         | 1994-04-24 | [tinder,clash,facebook] |
| 2         | 1994-04-25 | [uno,whatsapp]          |

db fiddle视图
笔记
我会用 JOIN 而不是使用 , 因为 JOIN 强调连接两个表的关系。

相关问题