这是我的数据库的外观:
|| order || || status || || employees ||
========== ============== ===============
id id id
name current_status display_name
created_by date(timestamp)
date updated_by
我想要的是每个订单,订单详情和最新状态:
order.id // == status.id
order.name
order.date
order.created_by // = employees.id
status.current_status //latest status MAX(date)
employees.display_name //status.upated_by = employees.id
以下是一些示例数据:
==================================================================
|| order ||
==================================================================
|| id || || name || || created_by || || date ||
==================================================================
5487 || || Josh || || 1 || || 2013-24-05
5488 || || Kren || || 3 || || 2013-22-04
====================================================================
|| status ||
===================================================================
|| id || ||current_status || || date || || updated_by
===================================================================
|| 5487 || || Packaged || || 2013-24-05 22-09 || 2
|| 5488 || || Packaged || || 2013-25-05 12-05 || 3
|| 5487 || || Shipped || || 2013-28-05 16-05 || 1
===================================================================
|| employees ||
==================================================================
|| id || || display_name ||
===================================================================
|| 1 || || Rick ||
|| 2 || || Dave ||
|| 3 || || Sydney ||
这是我尝试过的,但 current_status 不正确:
SELECT a.id, a.name, a.created_by, a.date, b.current_status, c.display_name
FROM id a INNER JOIN ( SELECT id, current_status, MAX(date) FROM status GROUP BY id) b
ON b.id=a.id INNER JOIN users c ON b.updated_by=c.id AND a.created_by = c.id
GROUP BY a.id
感谢您的时间和帮助。