我有两个表“ sample”和“ processes”,我想在一列中获取给定样本的所有过程。
表“示例”示例:
----------------------------------------
| 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查询做到这一点?怎么?
PS:我知道我可以使用以下方法获得给定样品的所有过程:
SELECT sample_id, timestamp, process_name
FROM sample, processes
WHERE sample.id = processes.sample_id
但这给了我太多不必要的行
答案 0 :(得分:1)
您可以尝试将GROUP_CONCAT
与CONCAT
功能一起使用。
模式(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] |
注意
我将使用JOIN
而不是,
,因为JOIN
强调有关连接两个表的关系。