1
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

运行后,返回结果为:

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

它应该返回的是

id  prod_ID   min_time
1   9         1200

最初以为加入有错误,经过多次加入测试,同样的错误结果。

SQLFiddle

SQLFiddle_2

SQLFiddle_3

SQLFiddle_2澄清我使用 Group By 因为我有多个 ID

SQLFiddle_3进行更多扩展。

在 SQLFiddle_3 上运行后,返回结果为:

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
4

2 回答 2

1

在您的查询中,您GROUP BY t3.id只有并且您不聚合 on 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
)

请参阅演示
结果:

> id | prod_ID | diff
> -: | ------: | ---:
>  1 |       9 | 1200
>  2 |       2 |  960
于 2020-10-21T16:16:22.273 回答
0

您的查询确实非常错误,您的内部查询本质上是列出时差,但随后您将所有这些出色的工作都扔掉,并且不加入或分组 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
于 2020-10-21T16:15:47.207 回答