我想从两个表中选择所有行,并从最后一个表mysql中选择一行
我的表格如下,
tbl_order
order_id order_no
-------- --------
1 1000
2 1001
3 1002
tbl_assign
assign_id order_id central_status
--------- -------- --------------
1 1 1
2 2 1
3 3 1
tbl_unit_status
status_id assign_id status_status
--------- --------- -------------
1 1 Work
2 2 Cutter
3 2 Stitch
4 1 Stitch
从上面的3表中,我希望结果为,
order_id order_no assign_id status_status
-------- -------- --------- -------------
3 1002 3 {null}
2 1001 2 Stitch
1 1000 1 Stitch
我尝试过以下代码,
SELECT * FROM tbl_order o LEFT JOIN tbl_assign a ON a.order_id = o.order_id LEFT JOIN (SELECT * FROM tbl_unit_status u ORDER BY u.status_id DESC LIMIT 1) uu ON uu.assign_id = a.assign_id WHERE a.central_status = 1 ORDER BY a.assign_id DESC
但结果是,
order_id order_no assign_id status_status
-------- -------- --------- -------------
3 1002 3 {null}
2 1001 2 {null}
1 1000 1 Stitch
哪里做错了。我已经尝试了很多。请帮我找到答案。谢谢。
答案 0 :(得分:1)
尝试这样:
SELECT o.*,u2.assign_id,u2.status_status FROM tbl_order o
LEFT JOIN tbl_assign a ON a.order_id = o.order_id LEFT JOIN
(SELECT u.assign_id,max(u.status_id) as maxid FROM tbl_unit_status u group by u.assign_id)
uu ON uu.assign_id = a.assign_id
LEFT JOIN tbl_unit_status u2 on u2.status_id = uu.maxid
WHERE a.central_status = 1 ORDER BY a.assign_id DESC
答案 1 :(得分:0)
试试这个
C:\Code\Java\Glassfish\glassfish3\glassfish\domains\domain1\config\domain.xml
使用SELECT * FROM tbl_order o LEFT JOIN tbl_assign a ON a.order_id = o.order_id
LEFT JOIN (SELECT * FROM tbl_unit_status u ORDER BY u.status_id DESC LIMIT 2)
uu ON uu.assign_id = a.assign_id WHERE a.central_status = 1 ORDER BY
a.assign_id DESC
,您只是与tbl_unit_status中包含assign_id 1的最后一行进行比较。