【问题标题】:Nested MySQL query failed with `Error Code 1060 Duplicate column name 'xxx'`嵌套 MySQL 查询失败,错误代码 1060 Duplicate column name 'xxx'`
【发布时间】:2021-05-17 13:59:16
【问题描述】:

所以我有三个表:tabe_1, table_2, table_3,我将使用字段A 来映射前两个表,因为它包含在table_1table_2 中,然后加入@987654325 @ 带有字段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,有人可以看看嵌套查询发生了什么吗?谢谢。

【问题讨论】:

  • 你在子查询中使用select *。列出子查询中的列。
  • 是的,请看上面的查询:FROM (select * from.......) AS output_table
  • 列出子查询中的列而不是使用select *。我认为我之前的评论很混乱。

标签: mysql sql mysql-workbench


【解决方案1】:

因为您的 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.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;

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

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) ? 不能,除非您在子查询中仅指定一个字段“A”。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      可能table_1table_2 至少有一个列存在于两个表中(您的列A)。因此,当您的子查询以select * from ... 执行时,它会返回两个具有相同名称的列。如果您只是单独执行此子查询,这不是问题,但您无法从该子查询的结果中查询

      将您的子查询重写为

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

      并确保仅从一个表中选择要加入的列(或存在于多个表中的列)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-27
        • 2021-11-03
        • 2014-03-19
        • 1970-01-01
        • 2017-04-08
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多