SQL 查询列名相同的两个表的内连接,字段列表中的列'exName'不明确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15036104/
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-09-01 13:51:35  来源:igfitidea点击:

Querying the inner join of two tables with the same column name, Column 'exName' in field list is ambiguous

sqlinner-joinambiguous

提问by Ben Pearce

I am querying the inner join of three tables using the following query.

我正在使用以下查询查询三个表的内连接。

Two of the tables have columns named "name1". I am getting the following error.

其中两个表具有名为“name1”的列。我收到以下错误。

Column 'exName' in field list is ambiguous

The "name1" columns are foreign key so the information should be identical. Can anyone suggest a compact way around this?

“name1”列是外键,因此信息应该相同。谁能建议一个紧凑的方法来解决这个问题?

$result = mysql_query("SELECT name1,name2,name3 FROM `table1` INNER JOIN `table2` ON table2.name1=table1.PrimaryKey INNER JOIN `table3` ON table3.name1=table1.PrimaryKey"); 

回答by Vincent Ramdhanie

You need to qualify your column names with the table names.

您需要使用表名来限定列名。

 SELECT table1.name1, table2.name1, etc.

回答by supergrady

You need to refer to the columns in your select list as:

您需要将选择列表中的列称为:

SELECT <table name>.name1, <table name>.name2, <table name>.name3

SELECT <table name>.name1, <table name>.name2, <table name>.name3

You can also give the tables an alias when you introduce them in the from clause to save some keystrokes and make things cleaner:

当你在 from 子句中引入它们时,你也可以给这些表一个别名,以节省一些击键并使事情更清晰:

SELECT 
     t1.name1
    ,t2.name2
    ,t3.name3
FROM table1 AS t1
INNER JOIN table2 AS t2
    ON t2.name1 = t1.PrimaryKey
INNER JOIN table3 AS t3
    ON t3.name1 = t1.PrimaryKey

回答by dud3

Maybe not the right question, but how would we be able to create something a like this:

也许不是正确的问题,但我们如何能够创建这样的东西:

Table a
-------
id | x | y 
1 | 2 | 3 



Table b
-------
id | a_id | x | y 
1  | 1    | 2 | 3



SQL

SQL

SELECT * FROM
JOIN a.id = b.a_id

Where the result would be like:

结果会是这样的:

array(
    a.id: 1,
    b.id: 1,
    a.x: 2
)

What's my point

我的意思是什么

The tables that have the same column namesget merged, and I guess the ID of the first tables wins.

具有相同的表column names被合并,我猜第一个表的 ID 获胜。

回答by xQbert

SELECT T1.name1,T2.name2,T3.name3 
FROM `table1` T1 
INNER JOIN `table2` T2 ON t2.name1=t1.PrimaryKey 
INNER JOIN `table3` T3 ON t3.name1=t1.PrimaryKey