Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将行与mysql中的其他行合并_Mysql - Fatal编程技术网

将行与mysql中的其他行合并

将行与mysql中的其他行合并,mysql,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-

我的实际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
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
我想将每个名称和描述的开始和结束合并到一行中。大概是这样的:

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
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方面的专家,所以也许有人可以帮助我

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

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

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要优化此设置,需要索引名、类型和时间戳。

请添加您的努力来解决此问题。请显示实际的时间戳,而不是xxx。@TimBiegeleisen刚刚添加了时间戳。将文本格式的表转换为SQL并非易事statements@RaymondNijland使用Rextester:-此查询。忽略这一点,我正在尝试一个gaps和islands查询。仔细观察OP的数据;你会发现这毫无意义。@TimBiegeleisen你的权利。。。缺少此查询,table1.name=table2.name,table2.type=end,则可以正常工作,但为什么输出中只有两条记录而不是三条?topicstarter的预期输出也显示两条记录@TimBiegeleisen,其中名称上的筛选器='xyz'。。如果您没有注意到示例数据有两个名称'xyz'和'zyx',则没有看到+1。据我所知,这几乎是一个缺口和孤岛问题。很好,你找到了一个解决方案,而不必使用解析函数。