如何在SQL中按多列连接两个表?

时间:2014-11-13 19:22:18

标签: mysql sql sql-server

我有两张表EvalulationValue

在两个表中,共有四列。但四个中有三个是相同的。换句话说,他们都有CaseNumFileNumActivityNum。除了这些列,EvaluationGradeValueScore

我希望通过CaseNumFileNumActivityNum将这两个合并到一个表中,这样我就有了一个包含Value和{{1}的5列新表在它里面。

我可以多次使用Score来执行此操作吗?

5 个答案:

答案 0 :(得分:19)

答案是肯定的:您可以使用内部联接 您可以在Common Columns上创建联接

select E.CaseNum, E.FileNum, E.ActivityNum,E.Grade,V.score from Evalulation E
inner join Value V
ON E.CaseNum=V.CaseNum and
E.FileNum=V.FileNum and 
E.ActivityNum=V.ActivityNum

创建表

Create table MyNewTab(CaseNum int, FileNum int, 
ActivityNum int,Grade int,score varchar(100))

插入值

Insert into MyNewTab Values(CaseNum, FileNum, ActivityNum,Grade,score)
select E.CaseNum, E.FileNum, E.ActivityNum,E.Grade,V.score from Evalulation E
inner join Value V
ON E.CaseNum=V.CaseNum and
E.FileNum=V.FileNum and 
E.ActivityNum=V.ActivityNum

答案 1 :(得分:4)

不,只需在1个内连接语句的“ON”子句中包含不同的字段:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

答案 2 :(得分:0)

您只需要进行一次加入:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

答案 3 :(得分:0)

你基本上想要的是:

SELECT e.*, v.Score
  FROM Evaluation e
LEFT JOIN Value v
ON v.CaseNum = e.CaseNum AND
v.FileNum = e.FileNum AND
v.ActivityNum = e.ActivityNum;

答案 4 :(得分:0)

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum