在MySQL中合并行与其他行

时间:2018-07-24 13:15:16

标签: mysql

我的实际mysql查询的输出如下:

name      type    desc         timestamp
xyz       start   desc1        2018-07-24 09:03:15
xyz       end     desc1        2018-07-24 10:31:57
xyz       start   desc2        2018-07-24 10:33:16
xyz       end     desc2        2018-07-24 10:53:27
zyx       start   desc1        2018-07-24 10:09:19
zyx       end     desc1        2018-07-24 10:24:34

我想将每个名称和desc的开始和结束合并为一行。像这样:

name       desc         start(timestamp)        end(timestamp)
xyz        desc1        2018-07-24 09:03:15     2018-07-24 10:31:57
xyz        desc2        2018-07-24 10:33:16     2018-07-24 10:53:27

我不是mysql的专家,所以也许有人可以帮助我

1 个答案:

答案 0 :(得分:1)

一个相关的子查询可能是获得所需结果的简便方法。

记住正确别名对于与相关子查询非常重要。

SELECT 
    table1.name,
    table1.desc,
    table1.timestamp AS 'start(timestamp)', 
    (SELECT table2.timestamp
     FROM table AS table2
     WHERE table1.timestamp < table2.timestamp
       AND table1.name = table2.name
       AND table2.type = 'end'
     ORDER BY table2.timestamp ASC
     LIMIT 1) AS 'end(timestamp)'
FROM    
    table AS table1
WHERE
    table1.type = 'start'
    AND table1.name = 'xyz'
ORDER BY 
    table1.timestamp ASC

p.s来优化此index(name, type, timestamp)