SQL:在两个内部联接之后分隔列名

时间:2012-11-11 20:39:50

标签: sql

SELECT *
FROM banhammer_bans
INNER JOIN banhammer_players AS player
    ON banhammer_bans.player_id = player.id
INNER JOIN banhammer_players AS admin
    ON banhammer_bans.creator_id = admin.id
ORDER BY created_at DESC

我从banhammer_players表中获得了三个id列和两个name列。我如何分离这些,以便我可以在我的PHP代码中使用它们?

banhammer_players包含两列,idname。 banhammer_bans有两列(player_idcreator_id),它们都与banhammer_players表匹配。

2 个答案:

答案 0 :(得分:1)

使用别名明确选择所有列。

SELECT banhammer_bans.id as bans_id, banhammer_players as players_id, ...
FROM banhammer_bans
INNER JOIN banhammer_players AS player
    ON banhammer_bans.player_id = player.id
INNER JOIN banhammer_players AS admin
    ON banhammer_bans.creator_id = admin.id
ORDER BY created_at DESC

答案 1 :(得分:0)

将查询中的别名用作:

   SELECT bans.id, player.name AS player_name, admin.name AS admin_name
   FROM banhammer_bans AS nans
   INNER JOIN banhammer_players AS player
   ON bans.player_id = player.id
   INNER JOIN banhammer_players AS admin
   ON bans.creator_id = admin.id
   ORDER BY created_at DESC;

您可以使用表格别名为select添加尽可能多的属性,以获取不明确的列(多个表中的同名列)。