从样本表中多次联接

时间:2018-10-17 20:36:07

标签: sql join

我有一个如下查询:

select a.id, b.score score2017, c.score score2018 
from table1 a
join table2 b
  on a.id=b.id and b.year=2017
join table2 c
  on a.id=c.id and c.year=2018

这将返回许多重复项。我应该如何构造这样的查询?

2 个答案:

答案 0 :(得分:0)

我刚刚意识到我有语法错误。没关系。

答案 1 :(得分:0)

score2017score2018属于哪个表?

SELECT a.id, b.score, c.score 
  FROM table1 a 
 INNER JOIN table2 b ON a.id = b.id AND b.year = 2017 
 INNER JOIN table c ON b.id = c.id AND c.year = 2018;

您将table2 b加入table1 a,然后依次将table3 c加入table2 b

出于可读性考虑,我可能还会将a.id标识为_id,将b.score标识为_bScore,将c.score标识为_cScore