创建测试表
-- 创建用户表
create table user(
u_id int(11),
u_name varchar(8),
h_id varchar(20)
);
-- 创建爱好表
create table hobby(
h_id tinyint(3),
h_name varchar(6)
);
插入测试数据
-- 插入用户数据
insert into user (u_id, u_name, h_id) values
(1, '张三', '1,3,4'),
(2, '李四', '2,5'),
(3, '王五', '2,4,5');
u_id | u_name | h_id |
---|
1 | 张三 | 1,3,4 |
2 | 李四 | 2,5 |
3 | 王五 | 2,4,5 |
-- 插入爱好数据
insert into hobby (h_id, h_name) values
(1, '打篮球'),
(2, '踢足球'),
(3, '玩游戏'),
(4, '弹钢琴'),
(5, '阅读');
h_id | h_name |
---|
1 | 打篮球 |
2 | 踢足球 |
3 | 玩游戏 |
4 | 弹钢琴 |
5 | 阅读 |
利用group_concat函数来实现一对多查询
-- 一对多查询语句,合并多数项
select user.*,group_concat(h_name) as hobbys from user left join hobby on find_in_set(hobby.h_id, user.h_id) group by u_id;
u_id | u_name | h_id | hobbys |
---|
1 | 张三 | 1,3,4 | 玩游戏,弹钢琴,打篮球 |
2 | 李四 | 2,5 | 踢足球,阅读 |
3 | 王五 | 2,4,5 | 踢足球,弹钢琴,阅读 |
group_concat函数默认使用逗号","进行连接,我们可以使用separator来指定连接字符
-- 用separator来指定连接字符
select user.*,group_concat(h_name separator '、') as hobbys from user left join hobby on find_in_set(hobby.h_id, user.h_id) group by u_id;
u_id | u_name | h_id | hobbys |
---|
1 | 张三 | 1,3,4 | 玩游戏、弹钢琴、打篮球 |
2 | 李四 | 2,5 | 踢足球、阅读 |
3 | 王五 | 2,4,5 | 踢足球、弹钢琴、阅读 |