php 内连接 2 个具有相同列名的表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16213054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:43:42  来源:igfitidea点击:

Inner join 2 tables with same column names

phpmysqlinner-join

提问by Lars Kaptein

I'm working on displaying the achievements from my minecraft server on my website. But I can't get it to work.

我正在努力在我的网站上显示我的 Minecraft 服务器的成就。但我无法让它工作。

function achievements() {
    global $id;
    $sql="SELECT * FROM achievements
           INNER JOIN stats ON achievements.type=stats.type
           INNER JOIN stats ON achievements.block=stats.block
           INNER JOIN stats ON achievements.data=stats.data
           INNER JOIN stats ON achievements.value=stats.value
           WHERE player_id = $id";
    $result=mysql_query($sql) or die(mysql_error());
    $rows=mysql_fetch_array($result);
}   

Will I be able to use $rows['achievements.type'];and $rows['stats.type'];to get the column "type" from the selected table, or is there a another way to do it?

我是否能够使用$rows['achievements.type'];$rows['stats.type'];从所选表中获取列“类型”,或者是否有另一种方法来做到这一点?

The column and table names are defined by the plugin I use, so the names can't be changed.

列名和表名由我使用的插件定义,因此无法更改名称。

回答by John Woo

the reason why it is not working is because (in my own opinion) the server is a little confused on where how it will handle the columns names properly. In order it to work, add an alias on every table that has the same name that you want to join as well as the columns, eg

它不工作的原因是(在我自己看来)服务器对它如何正确处理列名称有点困惑。为了使其工作,请在每个具有相同名称的表以及要加入的列上添加别名,例如

SELECT  achievements.*,
        a.Name as TypeName,
        b.Name AS BlockName,
        c.Name as DataName,
        d.Name AS ValueName
FROM    achievements
        INNER JOIN stats a ON achievements.type = a.type
        INNER JOIN stats b ON achievements.block = b.block
        INNER JOIN stats c ON achievements.data = c.data
        INNER JOIN stats d ON achievements.value = d.value
WHERE   player_id = $id

assuming you want to get the names for every specific columns.

假设您想获取每个特定列的名称

回答by Lars Kaptein

Give the columns you want to have while you SELECTthem an alias as example:

为您想要的列SELECT提供别名,例如:

SELECT `achievements`.`type` AS `Achieve-Type`
FROM `achievements`

Now you can get the values like this: $rows['Achieve-Type'];

现在你可以得到这样的值: $rows['Achieve-Type'];

回答by david99world

It's easier to alias the table names with...

为表名取别名更容易...

SELECT * FROM achievements AS ac INNER JOIN stats as st

You could even alias the results if you wish so they are more distinguishable when you select them from $rows

如果您愿意,您甚至可以为结果设置别名,以便在从中选择它们时更容易区分 $rows