0
我目前有4個表,我查詢列出訂單狀態。 表與相關領域像這樣在左連接查詢中獲取每個時間戳的最新記錄
+--------------+ +------------+ +----------+ +----------+
|Orders | | Customers | | Users | | Status |
+--------------+ +------------+ +----------+ +----------+
| id | | id | | id | | id |
| customer_id | | name | | name | | order_id |
| rep_id | +------------+ +----------+ | status |
+--------------+ | comments |
| date |Timestamp
| tech_id |
+----------+
使用下面的SQL我可以顯示訂單和狀態的列表。
SELECT
Orders.id AS orderid,
Customers.name AS CLIENT,
Users.name AS rep,
Status.status
FROM
Orders
LEFT JOIN
Customers ON Orders.customer_id = Customers.id
LEFT JOIN
Users ON Orders.rep_id = Users.id
LEFT JOIN
Status ON Orders.id = Status.order_id
我得到了這樣的東西。
+---------+----------+-------+--------+
| orderid | CLIENT | rep | status |
+---------+----------+-------+--------+
| 1 | Client 1 | Rep 1 | 1 |
| 2 | Client 2 | Rep 2 | 1 |
| 3 | Client 3 | Rep 1 | 1 |
| 4 | Client 4 | Rep 2 | 1 |
| 6 | Client 6 | Rep 4 | 1 |
| 1 | Client 1 | Rep 3 | 4 |
| 6 | Client 6 | Rep 4 | 4 |
+---------+----------+-------+--------+
我需要根據狀態表上最近的日期得到一個每個orderid的記錄。我覺得我很親密,但無法弄清楚。
見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-似乎對我來說是一個非常簡單的SQL查詢 – Strawberry
這個問題已經被回答了很多次。查看[tag:most-n-per-group]標籤。 –