计算字段后的值 return 不正确

Value return incorrectly after calculated field

SELECT
    t3.id,
    t3.prod_ID,
    MIN(diff) AS min_time
FROM
    (SELECT
         t1.id,
         (UNIX_TIMESTAMP(t2.time_stamp_2) - UNIX_TIMESTAMP(t1.time_stamp)) AS diff
     FROM 
         production t1
     LEFT JOIN 
         process t2 ON t1.id = t2.id
     HAVING 
         diff >= 0) tx
LEFT JOIN 
    production t3 ON t3.id = tx.id
GROUP BY
    t3.id

在 运行 之后,returned 结果是:

id  prod_ID   min_time
-----------------------
1   2         1200

它应该 return 而不是

id  prod_ID   min_time
1   9         1200

我一开始以为是join出错,多次join测试,同样的错误结果。

SQLFiddle

SQLFiddle_2

SQLFiddle_3

SQLFiddle_2 说明我使用 Group By 因为我有多个 ID

SQLFiddle_3展开更多。

在 SQLFiddle_3 上 运行 之后,returned 结果是:

id  prod_ID   min_time
-----------------------
1   2         1200
2   2         960
3   2         360

应该是

id  prod_ID   min_time
-----------------------
1   9         1200
2   2         960
3   3         360

你的查询确实是非常错误的,你的内部查询本质上是在列出时差,但是你把所有这些好的工作都扔掉了,不在 prod_id 上加入或分组,所以它基本上只是选择您插入到数据库中的第一个值。如果您切换插入数据的顺序,那么首先插入 prod_id 然后您会得到您想要的结果,但原因是错误的。

你的内部查询是这样的:

SELECT
    t1.id,
    t1.prod_id,
    (UNIX_TIMESTAMP(t2.time_stamp_2)-UNIX_TIMESTAMP(t1.time_stamp)) as diff
    FROM production t1
    left JOIN process t2
    ON t1.id = t2.id
   WHERE (UNIX_TIMESTAMP(t2.time_stamp_2)-UNIX_TIMESTAMP(t1.time_stamp)) > 0

如果您运行看到您想要的值:

id     prod_id    diff
1        2        1800
1        3        1380
1        9        1200

...但是您的外部查询对此没有任何作用。

有很多方法可以做到这一点,这里介绍一种简单的方法:

SELECT 
    t1.id,
    t1.prod_id,
    (UNIX_TIMESTAMP(t2.time_stamp_2)-UNIX_TIMESTAMP(t1.time_stamp)) as diff
    FROM production t1
    left JOIN process t2
    ON t1.id = t2.id
   WHERE (UNIX_TIMESTAMP(t2.time_stamp_2)-UNIX_TIMESTAMP(t1.time_stamp)) > 0
   ORDER BY 3
   LIMIT 1

在您的查询中您仅 GROUP BY t3.id 而您没有在 t3.prod_ID 上聚合,因此返回的值未定义。

我相信您不需要 GROUP BY,甚至不需要重新加入 production
试试这个:

SELECT t1.id, t1.prod_ID,
       (UNIX_TIMESTAMP(t2.time_stamp_2) - UNIX_TIMESTAMP(t1.time_stamp)) AS diff
FROM production t1 INNER JOIN process t2
ON t1.id = t2.id 
AND (t1.id, t1.prod_ID) = (
  SELECT p.id, p.prod_ID
  FROM production p
  WHERE p.id = t2.id AND (UNIX_TIMESTAMP(t2.time_stamp_2) - UNIX_TIMESTAMP(p.time_stamp)) >= 0
  ORDER BY (UNIX_TIMESTAMP(t2.time_stamp_2) - UNIX_TIMESTAMP(p.time_stamp)) LIMIT 1
)

参见demo
结果:

> id | prod_ID | diff
> -: | ------: | ---:
>  1 |       9 | 1200
>  2 |       2 |  960