开发者社区> 问答> 正文

sql合并多条记录为一条

obj_id    path                 type       group_num  
------     -------------        ------      -----------
8207    /images/as.jpg   S              0
8207    /images/al.jpg    L              0
8207    /images/bs.jpg   S              1
8207    /images/bl.jpg    L              1
8207    /images/cs.jpg    S              2
8207    /images/cl.jpg     L              2

想得到以下效果,用sql语句应该怎么实现?mysql数据库


obj_id    small_img         large_img         group_num

8207      /images/as.jpg       /images/al.jpg            0
8207      /images/bs.jpg       /images/bl.jpg            1
8207   /images/cs.jpg    /images/cl.jpg       2


下面是建表和造数据语句 , type表示图片类型,'S'是小图片,'L'是大图片

CREATE TABLE `t_images` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `obj_id` INT(11) DEFAULT NULL,
  `path` VARCHAR(255) DEFAULT NULL,
  `type` VARCHAR(2) DEFAULT NULL,
  `group_num` INT(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) 
INSERT INTO t_images (obj_id,path,TYPE,group_num)
VALUES
(8207,'/images/as.jpg','S',0),(8207,'/images/al.jpg','L',0)
,(8207,'/images/bs.jpg','S',1),(8207,'/images/bl.jpg','L',1)
,(8207,'/images/cs.jpg','S',2),(8207,'/images/cl.jpg','L',2)

展开
收起
小旋风柴进 2016-03-11 10:49:18 2876 0
1 条回答
写回答
取消 提交回答
  • 不知道 obj_id 是什么含义,看看下面的SQL,是否满足你的要求:


    select max(obj_id) as obj_id, max(small_img) as small_img, max(large_img) as large_img, group_num
    from (
    select

    obj_id, case when type = 'S' then path else ''  end as small_img, case when type = 'L' then path else '' end as large_img, group_num

    from t_images
    ) a group by a.group_num;

    -------- result ---------
    obj_id samll_img large_img group_num
    8207 /images/as.jpg /images/al.jpg 0
    8207 /images/bs.jpg /images/bl.jpg 1
    8207 /images/cs.jpg /images/cl.jpg 2



    
    select max(obj_id) as obj_id, max(small_img) as small_img, max(large_img) as large_img, group_num
    from (
      select
        obj_id, case when type = 'S' then path else ''  end as small_img, case when type = 'L' then path else '' end as large_img, group_num
      from t_images
    ) a group by a.group_num;
    
    2019-07-17 18:58:40
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载