在子查询中获取MAX输入日期

时间:2018-05-08 10:09:21

标签: mysql join mysqli subquery

我有一个正在运行的脚本,但并不是所希望的。我的目的是为plans数据库中account_manager_sellers列表中每个卖家选择最近输入的记录。

下面脚本的当前问题是:它返回最旧的记录而不是最新的记录,例如:它在2016年选择一条记录而不是2018年有时间戳的记录。(最终我需要更改在2017-01-01之前获取所有lastsale记录的WHERE子句。

简单数据库样本。

plans AKA(销售清单)

+----+------------------+-----------+
| id |   plan_written   | seller_id |
+----+------------------+-----------+
|  1 | 20/09/2016 09:12 |       123 |
|  2 | 22/12/2016 09:45 |       444 |
|  3 | 19/10/2016 09:07 |       555 |
|  4 | 02/10/2015 14:26 |       123 |
|  5 | 15/08/2016 11:06 |       444 |
|  6 | 16/08/2016 11:03 |       123 |
|  7 | 03/10/2016 10:15 |       555 |
|  8 | 28/09/2016 10:12 |       123 |
|  9 | 27/09/2016 15:12 |       444 |
+----+------------------+-----------+

account_manager_sellers(卖家名单)

+-----+----------+
| id  |   name   |
+-----+----------+
| 123 | person 1 |
| 444 | person 2 |
| 555 | person 3 |
+-----+----------+

使用当前代码

SELECT p.plan_written, p.seller_id
FROM plans AS p NATURAL JOIN (
         SELECT   id, MAX(plan_written) AS lastsale
         FROM     plans
         GROUP BY seller_id
       ) AS t
JOIN account_manager_sellers AS a ON a.id = p.seller_id
WHERE  lastsale < "2018-05-08 00:00:00"

摘要

使用上面的代码和示例表,这段代码将返回这3个结果,而我们确实期望3个结果,MAX(plan_written)似乎没有跟随,我的猜测是它是使用GROUP子句,我不确定我们是否可以使用ORDER BY和LIMIT子句?

+--------------+------------------+
| seller_id    |   plan_written   |
+--------------+------------------+
|          123 | 16/08/2016 11:03 |
|          444 | 15/08/2016 11:06 |
|          555 | 03/10/2016 10:15 |
+--------------+------------------+

1 个答案:

答案 0 :(得分:0)

您的查询中的加入条件已关闭,您应该限制每个卖家的最长日期。此外,您无需加入account_manager_sellers表即可获得预期的输出:

SELECT p1.*
FROM plans p1
INNER JOIN
(
    SELECT
        seller_id, MAX(plan_written) AS max_plan_written
    FROM plans
    WHERE plan_written < '2018-05-08 00:00:00'
    GROUP BY seller_id
) p2
    ON p1.seller_id = p2.seller_id AND
       p1.plan_written = p2.max_plan_written;