我在加入时遇到麻烦。基本上,我只需要知道两个表中是否都存在“仓库”,而只需获取两个日期之间所需“仓库”的最后一个条目即可。
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)
这些是我的桌子
payments control
+---------------------------------------+ +-----------+
| id | warehouse | status | date | | warehouse |
+---------------------------------------+ +-----------+
|19006| 226975 | DUE |2018-06-26| | 226975 |
MAX ID-> |19066| 226975 | PAID |2018-06-27| | 226976 |
+---------------------------------------+ +-----------+
Result Obtained:
+--------------------------------------+
| warehouse | id | status | date |
+--------------------------------------+
| 226975 |19006 | DUE |2018-06-26|
+--------------------------------------+
In this case I'm obtaining the "first entry", the lower one (id: 19006) and I want "the last" (id: 19066) the max.
Result expected:
+--------------------------------------+
| warehouse | id | status | date |
+--------------------------------------+
| 226975 |19066 | PAID |2018-06-27|
+--------------------------------------+
有什么想法吗? 预先感谢。
答案 0 :(得分:2)
两个要求。
warehouse
列中都行。排除其他人。这是通过内部JOIN完成的。 payments
表中的最新条目。可以使用此子查询检索每个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
答案 1 :(得分:0)
我的版本与O. Jones略有不同。
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;