繁体   English   中英

使用自联接查找行之间的差异

[英]Using Self-Join to find differences between rows

我已经尝试找到该问题的解决方案,但是我发现的所有问题都提出了一个稍有不同的问题,或者没有足够的答案。 我有一个具有以下设置的表:

    fullvna

    +--------------+-------------+------+-----+---------+----------------+
    | Field        | Type        | Null | Key | Default | Extra          |
    +--------------+-------------+------+-----+---------+----------------+
    | startdate    | date        | YES  |     | NULL    |                |
    | starttime    | time        | YES  |     | NULL    |                |
    | id           | int(11)     | NO   | PRI | NULL    | auto_increment |
    +--------------+-------------+------+-----+---------+----------------+

我想找到每对连续行之间的时间差,因此id = 1的开始时间减去id = 2的开始时间(该表按相反的时间顺序排列)。 我基于在这里找到的查询进行查询: http : //www.mysqltutorial.org/mysql-tips/mysql-compare-calculate-difference-successive-rows/

    create table difference as SELECT 
                one.id,
                one.starttime,
                two.starttime,
                (one.starttime - two.starttime) AS diff
            FROM
                fullvna one
                    INNER JOIN
                fullvna two ON two.id = one.id + 1;

我收到以下打印输出,不确定是什么意思或我做错了什么:

    ERROR 1064 (42000): You have an error in your SQL syntax; check the
     manual that corresponds to your MySQL server version for the right
     syntax to use near '  one.starttime,
        two.starttime,
        (one.starttime - two.starttime' at line 3
  • 不要使用别名one因为它是一个关键字,请选择其他别名
  • 别名startime,因为在创建表中具有相同名称的两列将不起作用。
  • timediff(如评论中提到的其他人)

 CREATE TABLE difference as 
 SELECT a1.id
      , a1.starttime as OneStartTime
      , a2.starttime as TwoStartTime
      , TIMEDIFF(a1.starttime, a2.starttime) AS diff
 FROM fullvna a1
 INNER JOIN fullvna a2
    ON a2.id = a1.id + 1;

您有隐藏的字符显示为空格,但不是,而是导致错误。 从我的答案中复制查询。 正如Juan所建议的那样,建议使用TIMEDIFF()函数而不是减去它们:

CREATE TABLE difference AS
SELECT one.id,
       one.starttime AS starttime,
       two.starttime AS endtime,
       TIMEDIFF(one.starttime, two.starttime) AS diff
FROM fullvna one
INNER JOIN fullvna two ON two.id = one.id + 1;

编辑正如xQbert所述,您需要为starttime列使用不同的名称,因此我相应地更正了上面的查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM