如何编写从多个表返回值的SQL SELECT语句?

时间:2013-03-18 21:58:16

标签: mysql sql select

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

人员表包括:人员ID,姓名,出生日期和其他一些不必要的值。 coach表包含:coach id和一些其他不必要的值。 玩家表包括:玩家ID,加入日期,加入。 游戏桌包括:教练ID,玩家ID,游戏日期,游戏时间,游戏持续时间。

人员表基本上存储了教练和球员的所有名字和主要细节。表格链接正确。

我尝试了各种各样的陈述,但我完全糊涂了自己。这个例子有些蹩脚,我还有别的东西,但不知道怎么回事。

e.g。

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;

2 个答案:

答案 0 :(得分: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 Fiddle Demo

答案 1 :(得分: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'