使用left join with min

时间:2015-08-24 10:19:46

标签: mysql sql left-join min

我正在尝试使用左连接和日期连接两个表。

我的SQL查询

SELECT
    ord.`ordernumber` bestellnummer,
    his.`change_date` zahldatum
FROM
    `s_order` ord
LEFT JOIN
    `s_order_history` his ON ((ord.`id`=his.`orderID`) AND (ord.`cleared`=his.`payment_status_id`)) #AND MIN(his.`change_date`)
WHERE
    ord.`ordertime` >= \''.$dateSTART.'\' AND ord.`ordertime`  <= \''.$dateSTOP.'\'' ;

s_order

+----+---------------------+---------+-------------+
| id |     ordertime       | cleared | ordernumber |
+----+---------------------+---------+-------------+
|  1 | 2014-08-11 19:53:43 |       2 |         123 |
|  2 | 2014-08-15 18:33:34 |       2 |         125 |
+----+---------------------+---------+-------------+

s_order_history

+----+-------------------+-----------------+---------+---------------------+
| id | payment_status_id | order_status_id | orderID | orderID change_date |
+----+-------------------+-----------------+---------+---------------------+
|  1 |                 1 |               5 |       1 | 2014-08-11 20:53:43 |
|  2 |                 2 |               5 |       1 | 2014-08-11 22:53:43 |
|  3 |                 2 |               7 |       1 | 2014-08-12 19:53:43 |
|  4 |                 1 |               5 |       2 | 2014-08-15 18:33:34 |
|  5 |                 1 |               6 |       2 | 2014-08-16 18:33:34 |
|  6 |                 2 |               6 |       2 | 2014-08-17 18:33:34 |
+----+-------------------+-----------------+---------+---------------------+

通缉结果:

+-------------+---------------------+
| ordernumber |     change_date     |
+-------------+---------------------+
|         123 | 2014-08-11 22:53:43 |
|         125 | 2014-08-17 18:33:34 |
+-------------+---------------------+

我遇到的问题是只获取日期,其中已清除/ payment_status_id值已在s_order中更改。我目前获得payment_status_id与当前清算值匹配的所有日期,但我只需要首先发生的日期。

这只是实际查询的摘录,因为原始查询的时间要长得多(大多数是左连接和更多表)。

3 个答案:

答案 0 :(得分:0)

MIN是一个聚合函数,所以你不能像以上那样在JOIN中直接使用它。您也没有将它与JOIN中的值进行比较。

你想要做的事情如下:

his.`change_date` = (SELECT MIN(his.`change_date`) FROM s_order_history where ord.`id` = his.`orderID`)

JOIN

答案 1 :(得分:0)

试试这个:

select s_order.ordernumber, min(s_order_history.change_date)
from s_order left join s_order_history
on s_order.id = s_order_history.orderID
   and s_order.cleared = s_order_history.payment_status_id
group by s_order.order_id

答案 2 :(得分:0)

SELECT ord.`ordernumber` bestellnummer,
MIN( his.`change_date` ) zahldatum
...
GROUP BY ord.`ordernumber`