表格详细信息:
CREATE TABLE `table1` (
`user` VARCHAR(50) NULL DEFAULT NULL,
`id` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
;
INSERT INTO `table1` (`user`, `id`) VALUES ('bob', '1');
INSERT INTO `table1` (`user`, `id`) VALUES ('bob', '2');
INSERT INTO `table1` (`user`, `id`) VALUES ('kev', '3');
INSERT INTO `table1` (`user`, `id`) VALUES ('kev', '4');
CREATE TABLE `table2` (
`id` VARCHAR(50) NULL DEFAULT NULL,
`data1` VARCHAR(50) NULL DEFAULT NULL,
`data2` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
;
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('1', 'a', 'a1');
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('1', 'b', 'b1');
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('1', 'b', 'c1');
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('2', 'a', 'd1');
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('2', 'b', 'e1');
INSERT INTO `table2` (`id`, `data1`, `data2`) VALUES ('3', 'g', 'f1');
CREATE TABLE `table3` (
`id` VARCHAR(50) NULL DEFAULT NULL,
`data11` VARCHAR(50) NULL DEFAULT NULL,
`data22` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
;
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('1', 'a10', 'a11');
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('1', 'b10', 'b11');
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('1', 'c10', 'c11');
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('2', 'd10', 'd11');
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('2', 'e10', 'e11');
INSERT INTO `table3` (`id`, `data11`, `data22`) VALUES ('3', 'f10', 'f11');
我尝试过的查询是:
select
t1.user,
t1.id,
group_concat(t2.data1 ) d1,
group_concat( t2.data2) d2,
group_concat( t3.data11 ) d11,
group_concat(t3.data22 ) d22
from table1 t1
left join table2 t2
on t2.id = t1.id
left join table3 t3
on t3.id = t1.id
where t1.user='bob' group by t1.id;
但是我在d1,d2,d11,d22中获得了多个数据,并且由于第二次左连接
预期输出:
+-------+------+------------+-----------+---------------+---------------+
| user | id | d1 | d2 | d11 | d22 |
+-------+------+------------+-----------+---------------+---------------+
| bob | 1 | a,b,b | a1,b1,c1 | a10,b10,c10 | a11,b11,c11 |
| bob | 2 | a,b | d1,e1 | d10,e10 | d11,e11 |
+-------+------+------------+-----------+---------------+---------------+
实际上我是使用jdbc将数组数据从api存储到mysql,我已插入数据 现在我必须在三个表中检索这些数据并形成数组格式并将其发送到Web api,所以这里有人知道如何执行此操作吗? 我需要做一个嵌套查询吗?
答案 0 :(得分:0)
您可以将派生表联接到首先进行聚合的子查询中。
SELECT t1.user,
t1.id,
t2.d1,
t2.d2,
t3.d11,
t3.d22
FROM table1 t1
LEFT JOIN (SELECT t2.id,
group_concat(t2.data1) d1,
group_concat(t2.data2) d2
FROM table2 t2
GROUP BY t2.id) t2
ON t2.id = t1.id
LEFT JOIN (SELECT t3.id,
group_concat(t3.data11) d11,
group_concat(t3.data22) d22
FROM table3 t3
GROUP BY t3.id) t3
ON t3.id = t1.id
WHERE t1.user = 'bob';