Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

如何将 MySQL 一对多关联结果显示在一行的多个字段?

表结构

CREATE TABLE `user`  (
  `shop_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(36) NULL DEFAULT NULL,
  `goods_name` varchar(36) NULL DEFAULT NULL,
  PRIMARY KEY (`shop_id`) USING BTREE
)

CREATE TABLE `shop`  (
  `user_id` varchar(36) NOT NULL,
  `user_name` varchar(36) NULL DEFAULT NULL,
  PRIMARY KEY (`user_id`) USING BTREE
)

数据

insert into user VALUES(UUID(),'A'),(UUID(),'B');
insert into shop(user_id,goods_name) VALUES('095ed60c-a4b1-11ea-8a65-1f70d6dfdbad','Goods_A'),('095ed60c-a4b1-11ea-8a65-1f70d6dfdbad','Goods_B');

需求

user 表对 shop 表示一对多的关系,name 为 A 的用于在 shop 表中可以关联到两条数据。

select user_name,goods_name from user
left join shop on shop.user_id=user.user_id
where user_name='A'

上面这条 SQL 的结果是:

goods_id goods_name
---------------------
A         Goods_A
A         Goods_B

现在的需求是把这两条放到同一行中,像下面这样:

goods_id goods_name1 goods_name2
-------------------------------
A         Goods_A     Goods_B

还得考虑查询效率的问题,请问这个查询语句该怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

一般来说直接给后端进行拼装,如果非要用sql的话,mysql的话使用group_concat,你可以了解一下数据库的列转行,你可以看看是不是符合你的需求

select?id,group_concat(name)?from?aa?group?by?id;

select user_name,group_concat(goods_name) as goods_name_list  from user
left join shop on shop.user_id=user.user_id
where user_name='A' group?by user_name
goods_id goods_name_list
A Goods_A,Goods_B

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...