0

我有四张桌子:人、教练、球员、比赛。我需要编写一个 SQL SELECT 语句,它将返回:我的身份证、姓名、出生日期、加入日期、我注册的教练的姓名,以及比赛的日期、时间和持续时间。

person 表包括:person id、name、出生日期和一些其他不必要的值。Coach 表包括:coach id 和一些其他不必要的值。玩家表包括:玩家id、加入日期、加入者。比赛表包括:教练ID、球员ID、比赛日期、比赛时间、比赛时长。

person 表基本上存储了教练和球员的所有姓名和主要详细信息。这些表已正确链接。

我尝试了各种说法,但我自己完全糊涂了。这个例子有点蹩脚,我还有别的东西,但不知道该怎么做。

例如

SELECT person_id, full_name, date_of_birth, join_date
FROM (person JOIN player ON player_id = person_id)
WHERE person_id='100' AND person_id, full_name
FROM (person JOIN coach ON coach_id = person_id);

这些是 CREATE 语句:

CREATE TABLE person (
        person_id          CHAR(10)    NOT NULL,
        full_name          VARCHAR(54)    NOT NULL,
        date_of_birth      DATE,
        sex                CHAR(1),
  PRIMARY KEY (person_id)
) engine innodb;
CREATE TABLE coach (
        coach_id          CHAR(10)    NOT NULL,
        phone_no           CHAR(10)    NOT NULL,
        hall_no            CHAR(4)    NOT NULL,
  PRIMARY KEY (coach_id),
  FOREIGN KEY (coach_id) REFERENCES person (person_id)
) engine innodb;
CREATE TABLE player (
        player_id        CHAR(10)    NOT NULL,
        join_date   DATE        NOT NULL,
        joined_with   CHAR(10),
  PRIMARY KEY (player_id),
  FOREIGN KEY (player_id) REFERENCES person (person_id),
  FOREIGN KEY (joined_with) REFERENCES coach (coach_id)
) engine innodb;
CREATE TABLE game (
        coach_id        CHAR(10)    NOT NULL,
        player_id       CHAR(10)    NOT NULL,
        game_date        DATE        NOT NULL,
        game_time        TIME        NOT NULL,
        game_duration    INTEGER    DEFAULT 10,
  PRIMARY KEY (coach_id, player_id, game_date, game_time),
  FOREIGN KEY (coach_id) REFERENCES coach (coach_id),
  FOREIGN KEY (player_id) REFERENCES player (player_id)
) engine innodb;
4

2 回答 2

1

你的 SQL 很差。看起来您正在尝试使用以下几个INNER JOINs

SELECT p.person_id, p.full_name, p.date_of_birth, pl.join_date, 
  c.coach_id, p2.full_name as coach_name, g.*
FROM person p
    JOIN player pl ON p.person_id = pl.player_id        
    JOIN game g ON p.person_id = g.player_id
    JOIN coach c ON c.coach_id = g.coach_id
    JOIN person p2 on c.coach_id= p2.person_id          
WHERE p.person_id='1' 
ORDER BY p.person_id, p.full_name

如果您不需要教练的名字,您将不需要第二次重新加入人员——我只是认为这将是有用的信息。

SQL 小提琴演示

于 2013-03-18T22:12:33.370 回答
0

我希望这有帮助。

SELECT person.person_id, person.full_name, person.date_of_birth, player.join_date 
 FROM person
INNER JOIN player
   ON player.player_id = person.person_id
WHERE person.person_id = '100'
于 2013-03-18T22:06:12.163 回答