在sql中选择名称和姓氏

时间:2015-05-26 20:03:24

标签: sql

所以我有四张桌子:

Team:
(PK) ID
Name

Player:
(PK) ID
(FK) Person

PlayerContract:
(PK) ID
(FK) Player
(FK) Team

Person:
(PK) ID
Name
Surname

我必须选择X队中球员的所有姓名和姓氏。我该怎么做?我想这样做:

SELECT 
  name, 
  surname 
FROM 
 Person 
WHERE 
  ID = SELECT Person 
       FROM Player 
       WHERE ID = SELECT Player 
                  FROM PlayerContact 
                  WHERE Team = SELECT ID 
                               FROM Team 
                               WHERE Name = "X";

可以吗?

2 个答案:

答案 0 :(得分:1)

不,不行,您可以轻松测试您的代码。无论如何,你需要做的是JOIN你的桌子:

SELECT  pe.Name,
        pe.Surname
FROM Player AS pl
INNER JOIN PlayerContract AS pc
    ON pl.ID = pc.Player
INNER JOIN Team AS t
    ON pc.Team = t.ID
INNER JOIN Person AS pe
    ON pc.Person = pe.ID
WHERE t.Name = 'X'

答案 1 :(得分:0)

它可以用于将子查询括在括号中:

SELECT 
  name, 
  surname 
FROM 
 Person 
WHERE 
  ID = (SELECT Person 
       FROM Player 
       WHERE ID = (SELECT Player 
                  FROM PlayerContact 
                  WHERE Team = (SELECT ID 
                               FROM Team 
                               WHERE Name = "X")));

请注意,结果可能与JOIN不同,例如,如果某个玩家在多个团队中(在这种情况下,上面的查询将无效,因为第二个子查询将返回两个记录)。