如何连接不同表的某些列?

时间:2018-08-29 19:40:51

标签: sql

学生表1

ID      Name     Surname        School Number     Class Number   ClassBranch
-----------------------------------------------------------------------------
113     Jane      Smith               19                4               A
121     John      Konl                42                5               B   
331     Albert    Smith               61                4               A
742     Jack      Ronal               52                5               B
759     Jan       Ronal               84                6               C

学生表2

ID     Name     Surname       School Number      Class Number   Class Branch
-----------------------------------------------------------------------------
113    Jane     Smith              11               4             D 
151    John     Konl               18               4             D 
804    Albert   Smith              26               5             F 
605    Jack     Ronal              32               5             F 
785    Jan    Ronal               87               8              L

创建学生表格

ID    Name   Surname   School Number    Class Number    Class Branch        
--------------------------------------------------------------------
113   Jane   Smith      NULL                 NULL          NULL
151   John   Konl       NULL                 NULL          NULL
804   Albert Smith      NULL                 NULL          NULL
605   Jack   Ronal      NULL                 NULL          NULL
NULL  NULL   NULL        11                    4             D  
NULL  NULL   NULL        18                    4             D  
NULL  NULL   NULL        26                    5             F  
NULL  NULL   NULL        32                    5             F  

我想要这张桌子

   ID    Name   Surname    School Number   Class Number   Class Branch

   113   Jane   Smith           11              4               D

   151   John   Konl           18              4               D

   804   Albert Smith          26              5               F

   605   Jack   Ronal          32              5               F

我想让学生表1 ---> ID,姓名,姓氏学生表2->学校编号,班级编号和班级分支机构joın.butjoın不成功。删除了分支A和B,并添加了D,F。

第一个表ID,名称,姓氏(三列)和第二个表的学校编号,班级编号,班级分支联接。

Where条件:

  • 已删除的列-> 4-A和5-B
  • 添加列-> 4- D和5- F

如何编写查询?

2 个答案:

答案 0 :(得分:1)

现在您已经完全更改了原始表,这应该是一个简单的JOIN

SELECT t2.id, t1.name, t1.surname, t2.SchoolNumber, t2.ClassNumber, t2.ClassBranch
FROM Student1 AS t1
JOIN Student2 AS t2 ON t1.name = t2.name AND t1.surname = t2.surname

DEMO

答案 1 :(得分:0)

要获得那些结果?

1)复杂的方法。通过加入他们。

SELECT 
s2.ID, 
s1.Name, s1.Surname,
s2."School Number",  s2."Class Number", s2.ClassBranch
FROM Student1 AS s1
JOIN Student2 AS s2 ON (s2.Name = s1.Name AND s2.Surname = s1.Surname)
WHERE s1."Class Number" IN (4, 5);

2)简单的方法,仅从第二个表中选择

SELECT *
FROM Student2
WHERE "Class Number" IN (4, 5);

在SQL Fiddle here上进行测试