sql在左表中按列左外连接顺序,但保留所有行

时间:2013-04-05 09:15:51

标签: sql join

我有以下内容:

SELECT 
table1.id
FROM
table1 
LEFT OUTER JOIN table2 ON table2.table1_id = table1.id
WHERE
(table1.entry_id=2) 
AND 
parent_id=0 
ORDER BY 
SUM(table2.column1) - SUM(table2.column2)

工作正常,直到我添加'order by',我需要它来获取table1中的所有相关行,即使它们在table2中有不匹配的行,也会将它们放在底部。

1 个答案:

答案 0 :(得分:0)

请改为尝试:

SELECT 
  t1.id
FROM table1 AS t1
LEFT OUTER JOIN
(
   SELECT table1_id, SUM(column1) sum1, SUM(column2) sum2
   FROM table2 
   GROUP BY table1_id
) AS t2  ON t2.table1_id = t.id
        AND t1.entry_id  = 2 
        AND t1.parent_id = 0 
ORDER BY t2.sum1 - t2.sum2;