在两个日期之间连接max id

x6492ojm  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(288)

我在加入时遇到了麻烦。基本上,我只需要知道“仓库”是否存在于两个表中,但只需获取两个日期之间所需“仓库”的最后一个条目。

Select c.warehouse, p.id, p.status FROM control c LEFT JOIN payment p ON c.warehouse = p.warehouse WHERE p.date BETWEEN '2018-06-26' AND '2018-06-27'

我也试过(上面写着:组函数的使用无效):

Select c.warehouse, p.id, p.status FROM control c LEFT JOIN payment p ON c.warehouse = p.warehouse WHERE p.date BETWEEN '2018-06-26' AND '2018-06-27' && p.id = MAX(p.id)

这些是我的table:

payments                       control
             +---------------------------------------+    +-----------+
             | id  |  warehouse  | status |   date   |    | warehouse |
             +---------------------------------------+    +-----------+
             |19006|    226975   |   DUE  |2018-06-26|    |   226975  |
    MAX ID-> |19066|    226975   |   PAID |2018-06-27|    |   226976  |
             +---------------------------------------+    +-----------+

获得的结果:

+--------------------------------------+
| warehouse |  id  | status |   date   |
+--------------------------------------+
|  226975   |19006 |  DUE   |2018-06-26|
+--------------------------------------+

在这种情况下,我得到的是“第一个条目”,低一个(id:19006),我想要“最后一个”(id:19066)的最大值。
预期结果:

+--------------------------------------+
| warehouse |  id  | status |   date   |
+--------------------------------------+
|  226975   |19066 |  PAID  |2018-06-27|
+--------------------------------------+

有什么想法吗?

dw1jzc5e

dw1jzc5e1#

两个要求。
warehouse 列在两个表中。排除其他人。这是通过内部连接完成的。
来自 payments table。这个 id 每个人的最新记录 warehouse 可以使用此子查询检索。

SELECT MAX(id) id, warehouse 
    FROM payments
   GROUP BY warehouse

综合起来:

SELECT p.warehouse, p.id, p.status, p.date
    FROM payments p
    JOIN ( SELECT MAX(id) id, warehouse 
             FROM payments
            GROUP BY warehouse
         ) mm ON p.id = mm.id AND p.warehouse = mm.warehouse
    JOIN control c ON p.warehouse = c.warehouse
iaqfqrcu

iaqfqrcu2#

我的版本与o略有不同。琼斯。

SELECT *
FROM control c
LEFT JOIN payments p ON p.warehouse=c.warehouse AND
                        p.date = (SELECT MAX(p1.date) 
                                  FROM payments p1 
                                  WHERE p1.warehouse=c.warehouse)
WHERE p.date IS NOT NULL;

相关问题