嵌套 MySQL 查询失败,错误代码 1060 列名称重复 'xxx'

Nested MySQL query failed with `Error Code 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

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

可能 table_1table_2 至少有一个列同时存在于两个 table 中(您的列 A)。因此,当您的子查询作为 select * from ... 执行时,它 returns 具有相同名称的两列。如果你只是单独做这个子查询,这不是问题,但是你不能从那个子查询的结果中查询

将您的子查询重写为

select t1.A, t1.B, t1.C, t2.whatever, t3.idontknow, ...
....

并确保 select 您要加入的列(或存在于多个 table 中的列)仅来自一个 table.

因为您 SQL 查询需要区分子查询字段的能力,以便将其视为 table 类型的记录源。

下面是一个例子:

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.C and t2.A/t2.D and t3.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;

所以,为了避免这个问题,select 确切地说,您需要从子查询中获取哪些字段,例如:

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;

为了更清楚,假设你想加入另一个 table 与你的子查询((subquery) AS output_table join another_table t4 on t4.A = output_table.A,MySQL 引擎如何从 output_table 它应该用于在 t1.A (0) 和 T3.A (1) 之间加入 another_table 吗?不能,除非您在子查询中仅指定一个字段 'A' .

在您的子查询中,您在 t1 和 t2 中有 A 列和 A 列,因此存在歧义。 为该列尝试别名,这应该会使事情变得简单。