使用相同数据但不同列名连接表

时间:2018-04-19 21:37:52

标签: sql

coachID和teamCoach包含相同的数据,但具有不同的列名。因此我无法加入他们。我该怎么办?

SELECT tblCoaches.coachID AS "Coach ID", 
       tblCoaches.coachName AS "Coach Name", 
       tblCoaches.coachCity AS "Coach City", 
       tblTeams.teamName AS "Team Name"
FROM tblCoaches
INNER JOIN tblTeams ON **tblCoaches.coachID = tblTeams.teamCoach**
      AND (coachID IN (SELECT teamCoach FROM tblTeams))
WHERE teamIsRec IS NULL;

2 个答案:

答案 0 :(得分:0)

此结构应该有效

    SELECT
      tblCoaches.coachID AS "Coach ID",
      tblCoaches.coachName AS "Coach Name",
      tblCoaches.coachCity AS "Coach City",
      tblTeams.teamName AS "Team Name"
    FROM tblCoaches
    INNER JOIN tblTeams
      ON tblCoaches.coachID = tblTeams.teamCoach   -- IDs that linked the tables
    WHERE teamIsRec IS NULL;

答案 1 :(得分:0)

如果您想在特定列上进行连接:

select * from table2 JOIN table1 ON table2.id = table1.id_a

在你的情况下,我认为该行

AND (coachID IN (SELECT teamCoach FROM tblTeams))

不执行任何逻辑,因为INNER JOIN仅接受两个表中的列值。所以你的语法应该是这样的:

SELECT tblCoaches.coachID AS "Coach ID", tblCoaches.coachName AS "Coach Name", tblCoaches.coachCity AS "Coach City", tblTeams.teamName AS "Team Name"
FROM tblCoaches
INNER JOIN tblTeams ON tblCoaches.coachID = tblTeams.teamCoach
WHERE teamIsRec IS NULL;