首页 > 解决方案 > 嵌套 MySQL 查询失败,错误代码 1060 Duplicate column name 'xxx'`

问题描述

所以我有三个表:tabe_1, table_2, table_3,我将使用一个字段A来映射前两个表,因为它包含在两个 table_1table_2中,然后加入table_3与字段BC,然后在上面添加一些过滤器(例如:where语句) ,查询是:

SELECT *
FROM 
(select *
from table_1 t1 
join table_2 t2 
on t1.A = t2.A
join table_3 t3
on t1.B  = t3.B 
and t1.C = t3.C) AS output_table

WHERE output_table.xx = xxx

这给了我错误:Error Code: 1060. Duplicate column name 'A'

但如果我只查询子查询:

select *
from table_1 t1 
join table_2 t2 
on t1.A = t2.A
join table_3 t3
on t1.B  = t3.B 
and t1.C = t3.C

这将返回 output_table,有人可以看看嵌套查询发生了什么吗?谢谢。

标签: mysqlsqlmysql-workbench

解决方案


因为您的 SQL 查询需要能够区分子查询字段才能将其视为表类型记录源。

这是发生的事情的一个例子:

with table_1 as (select 0 A, 0 B, 0 C),
     table_2 as (select 0 A, 0 D),
     table_3 as (select 1 A, 0 B, 0 C)
SELECT *
FROM 
(select *
from table_1 t1 
join table_2 t2 
on t1.A = t2.A
join table_3 t3
on t1.B  = t3.B 
and t1.C = t3.C) AS output_table
WHERE output_table.D = 0;

这失败了,因为子查询具有字段 t1.A/t1.B/t1.Ct2.A/t2.Dt3.A/t3.B/t3.C。

如果不将其设为子查询,则 MySQL 引擎不需要区分字段,并且可以不区分所有字段的输出记录。从您的情况来看,有效的查询:

with table_1 as (select 0 A, 0 B, 0 C),
     table_2 as (select 0 A, 0 D),
     table_3 as (select 1 A, 0 B, 0 C)
select *
from table_1 t1 
join table_2 t2 
on t1.A = t2.A
join table_3 t3
on t1.B  = t3.B 
and t1.C = t3.C;

因此,为避免该问题,请从子查询中准确选择您需要的字段,如下所示:

with table_1 as (select 0 A, 0 B, 0 C),
     table_2 as (select 0 A, 0 D),
     table_3 as (select 1 A, 0 B, 0 C)
SELECT *
FROM 
(select t1.*, t2.D
from table_1 t1 
join table_2 t2 
on t1.A = t2.A
join table_3 t3
on t1.B  = t3.B 
and t1.C = t3.C) AS output_table
WHERE output_table.D = 0;

更清楚地说,假设您想将另一个表与您的子查询 ( ) 连接起来(subquery) AS output_table join another_table t4 on t4.A = output_table.A,MySQL 引擎如何确定它应该使用 output_table 中的哪个字段 A 来连接 t1.A (0) 和 T3.A (1) 之间的 another_table ? 不能,除非您在子查询中仅指定一个字段“A”。


推荐阅读