左连接一行中的两个值

时间:2017-04-16 14:51:00

标签: php mysql

matches包含以下列:

id, teamA, teamB

teams包含:

id, name

我想输出两个团队,并设法做到这一点:

$sql1 = SELECT teams.name FROM matches LEFT JOIN teams ON matches.teamA = teams.id
$sql2 = SELECT teams.name FROM matches LEFT JOIN teams ON matches.teamb = teams.id

然后我用while循环输出它:

echo $sql1->name, $sql2->name

尝试一个查询时遇到的问题是,团队名称每行只能输出一次。

如何使用一个查询?

1 个答案:

答案 0 :(得分:2)

SELECT team1.name as team1name, // Select the first team name from the table aliased as team1, aliasing that column as team1
       team2.name as team2name  // Select the second team name from the table aliased as team2, aliasing that column as team2
  FROM matches
  LEFT JOIN teams team1         // Alias our first join to teams on teamA as team1
    ON matches.teamA = team1.id
  LEFT JOIN teams team2         // Alias our second join to teams on teamB as team2
    ON matches.teamB = teams2.id

当您执行此查询时,您应该返回2个团队名称,一个别名为team1name,另一个为team2name;因此,当您将这些检索到PHP时,它们将具有这些别名列名

DEMO