所以我有三个表:tabe_1、table_2、table_3
,我将使用字段 A
来映射前两个表,因为它包含在table_1
和 table_2
,然后将 table_3
与字段 B
和 C
连接,然后添加一些过滤器(例如: 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
这给了我错误:错误代码:1060。重复的列名称“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,有人可以看看嵌套查询发生了什么吗?谢谢。
最佳答案
因为您的 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 和 t2.A/t2.D 和 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) 之间的 another_table 连接?它不能,除非您在子查询中仅指定一个字段“A”。
关于mysql - 嵌套 MySQL 查询失败,错误代码为 `Error Code 1060 Duplicate column name ' xxx'`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67571197/