SQL查询将2个相同的表合并为distinct

时间:2013-03-09 22:42:17

标签: sql merge distinct

我想将2个相同的表合并到一个表中并区分用户。 这两个表看起来像这样:

Table1
**************
id, user, total
1, 1, 7
2, 2, 10
3, 3, 14


Table2
**************
id, user, total
1, 1, 4
2, 2, 7
3, 3, 3

我希望得到这样的结果:

user, total1, total2
1, 7, 4
2, 10, 7
3, 14, 3

SQL查询应该如何显示?

1 个答案:

答案 0 :(得分:4)

您需要JOINuser上的表格:

select t1.user,
  t1.total,
  t2.total as total2
from table1 t1
inner join table2 t2
  on t1.user = t2.user

请参阅SQL Fiddle with Demo

如果您需要帮助学习JOIN语法,这里有一个很棒的visual explanation of JOINs(由Jeff Atwood编写)。

INNER JOIN语法将返回两个表之间匹配的所有行。

如果您想添加另一个表,那么您将只包含另一个JOIN。根据您的评论,您将使用:

select t1.user,
  t1.total,
  t2.total as total2,
  t3.department
from table1 t1
inner join table2 t2
  on t1.user = t2.user
inner join table3 t3
  on t1.user = t3.user
相关问题