如何在同一张桌子上进行双联接?
基本上,我想这样做:
1 - Sort all records in descending order by a order_date_last_revised column.
2 - Group those records by order_base_id column to eliminate duplicates.
3 - Match the id of those records and return all columns for them.
这是我的SQL,它不起作用:
SELECT
*
FROM sys_quote_master q1
LEFT JOIN sys_quote_master q2 ON q1.order_id = q2.order_id group by q2.order_base_id
LEFT JOIN sys_quote_master q3 ON q2.order_id = q3.order_id WHERE order_base_id="010313-6063" order by q3.order_date_last_revised desc;
基本上,当我尝试执行它时,我得到了这个:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN sys_quote_master q2 ON q1.order_id = q2.order_id order by q3.order_dat' at line 4
答案 0 :(得分:1)
如果放置了group by
,它就会出现:它必须出现在表之后和where子句之后(如果有的话):
SELECT *
FROM sys_quote_master q1
LEFT JOIN sys_quote_master q2 ON q1.order_id = q2.order_id
LEFT JOIN sys_quote_master q3 ON q2.order_id = q3.order_id
WHERE order_base_id="010313-6063"
group by q2.order_base_id
order by q3.order_date_last_revised desc;
但请注意,按现状划分的小组不会有用;您必须列出非聚合列的所有列才能按预期运行。
也许分组不是你想要的 - 考虑使用distinct
模仿重复:
select distinct *
from ...
-- and remove group by clause
答案 1 :(得分:0)
这个怎么样?
SELECT * FROM
sys_quote_master AS g1
JOIN (SELECT order_id, order_base_id, max(order_date_last_revised) as mostrecent
FROM sys_quote_master WHERE order_base_id="010313-6063" group by order_base_id) AS g2
ON g2.mostrecent = g1.order_date_last_revised
ORDER BY g1.order_id;