SQL:如何在连接两个表时获取原始排序

时间:2012-11-08 01:48:38

标签: sql

我有两张桌子

第一个看起来像这样:

Name|Sir Name|Adress
Max1|Musterma|Muster Street
Max2|Musterma|Muster Street
Max3|Musterma|Muster Street
Max4|Musterma|Muster Street
Max5|Musterma|Muster Street

第二个看起来像这样:

Name|Money
Max3|50.00
Max1|40.00
Max3|43.00
Max2|77.00
Max3|18.00
Max1|97.00
Max1|87.00

我想使用Left Join并像这样输出:

Max1|Musterma|Muster Street|40.00
Max1|Musterma|Muster Street|97.00
Max1|Musterma|Muster Street|87.00
Max2|Musterma|Muster Street|77.00
Max3|Musterma|Muster Street|50.00
Max3|Musterma|Muster Street|43.00
Max3|Musterma|Muster Street|18.00
Max4|Musterma|Muster Street|
Max5|Musterma|Muster Street|

我得到的是:

Max3|Musterma|Muster Street|50.00
Max1|Musterma|Muster Street|40.00
Max3|Musterma|Muster Street|43.00
Max2|Musterma|Muster Street|77.00
Max3|Musterma|Muster Street|18.00
Max1|Musterma|Muster Street|97.00
Max1|Musterma|Muster Street|87.00
Max4|Musterma|Muster Street|
Max5|Musterma|Muster Street|

我得到的是在第二(右)表的条目位置之后排序。

但我希望将列表排序

  1. 在第一个用户的位置之后
  2. 在第二次钱的位置之后
  3. 有谁能告诉我我还需要写什么?

2 个答案:

答案 0 :(得分:1)

在SQL的末尾添加order by子句。它看起来像这样:

order by Table1.Name, Table2.Money

答案 1 :(得分:0)

您可以按如下方式使用order by子句:

select name
     , sir_name
     , address
     , money
from   table1
left join table2 on (...)
ORDER BY name, money

我只是猜到了你的表和列的名称,因为你没有提供它们=)