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

时间:2017-07-11 14:56:04

标签: mysql

我已经尝试过找到这个问题的解决方案,但我发现的所有问题都要求稍微不同的问题,或者没有足够的答案。我有一个表格,其中包含以下设置:

    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

2 个答案:

答案 0 :(得分:3)

  • 请勿使用别名one,因为关键字选择不同的
  • 别名startime,因为create table中具有相同名称的两列不起作用。
  • 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;

答案 1 :(得分:2)

您有隐藏的字符显示为空格,但它们不是,它们导致错误。从我的答案中复制查询。正如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列使用不同的名称,因此我相应地更正了上述查询。