Left加入三个MySQL表

时间:2013-09-04 17:25:40

标签: php mysql

tbl_teams: team_id | TEAM_NAME
tbl_players: player_id | player_fname | player_sname | player_bplace | player_bdate
tbl_players_stats: player_id | season_id | player_squad_no | team_id | player_apps | player_goals

很抱歉,如果这是一个基本问题,但是从上面的所有MySQL表和列中我想加入表格,然后显示选择了season_id和team_id的结果。我需要像这样使用PHP:

player_squad_no | player_sname,player_fname | team_name | player_apps | player_goals

我在这里查看了一些示例,但仍然无法弄清楚如何使用三个单独的表编写MySQL查询以及如何在列名之前指定表名。我见过一些只有初始的例子。 tt.teams例如。是左加入的方式吗?

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

使用三个单独的表,您只需按以下方式编写连接:

SELECT *
FROM Table_A AS A
LEFT JOIN Table_B AS B USING(ID)
LEFT JOIN Table_C AS C USING(ID)

请注意,USING(column)ON A.column = B.column的一种语法替代方法,当您要加入的列在两个表中具有相同的名称时,您可以使用它们。

在上面的示例中,表格使用AS别名,以便您可以通过别名而不是完整的表名来引用它们。 (AS实际上是可选的;你可以在表格之后立即给出别名,如果你是通过角色付费的话。)尝试选择一个看起来有意义的别名;人们通常会这样做别名:

SELECT a.Name, b.State
FROM Customers AS a
LEFT JOIN Orders AS b
...etc.

但是如果您有更长的查询,那么您应该如何记住ab所指的表格?至少,别名Customers AS COrders AS O是有意义的;在某些情况下,我会更进一步:Registration AS REG,例如。随着JOIN越来越多的表一起使用,这变得越来越重要。

以下是编写查询的一种方法:

SELECT
    Stats.player_squad_no,
    CONCAT_WS(', ', Players.player_sname, Players.player_fname) AS player_full_name,
    Teams.team_name,
    Stats.player_apps,
    Stats.player_goals
FROM tbl_players AS Players
LEFT JOIN tbl_players_stats AS Stats USING(player_id)
LEFT JOIN tbl_teams AS Teams USING(team_id)

包含CONCAT_WS()功能,用于按照您希望显示的方式组合播放器的全名。由于此函数将输出一个名称混乱的列,我还给它一个别名。

答案 1 :(得分:0)

    SELECT player_squad_no , player_sname, player_fname,team_name, player_apps, player_goals
 FROM tbl_players_stats as s 
JOIN tbl_players as p ON s.player_id=p.player_id 
JOIN tbl_teams as t ON s.team_id=t.team_id

答案 2 :(得分:0)

这应该有效

SELECT tbl_players_stats.player_squad_no, 
    tbl_players.player_sname, 
    tbl_players.player_fname, 
    tbl_teams.team_name, 
    tbl_players_stats.player_apps, 
    tbl_players_stats.player_goals
FROM tbl_players 
    JOIN tbl_players_stats ON tbl_players.player_id = tbl_players_stats.player_id 
    JOIN tbl_teams ON tbl_teams.team_id = tbl_players_stats.team_id

答案 3 :(得分:-1)

Nothing Joining是一个简单的概念。但是我们应该为表使用适当的列。在选择要选择的列列表时,我们应该小心使用表别名。请尝试以下代码

select c.player_squad_no,b.player_sname,b.player_fname,a.team_name,c.player_apps,c.player_goals
  from tbl_teams a,tbl_players b,tbl_players_stats c
 where a.team_id=c.team_id 
   and b.player_id=c.player_id