mysql - 嵌套 MySQL 查询失败,错误代码 1060 Duplicate column name 'xxx'`
问题描述
所以我有三个表: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
这给了我错误: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,有人可以看看嵌套查询发生了什么吗?谢谢。
解决方案
因为您的 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”。
推荐阅读
- regex - 删除行尾字符的正则表达式
- swift - Swift:消失数组内容的神秘案例
- asynchronous - 如何在继续执行之前等待异步 chrome.storage.local.get() 完成
- python - Django:通过主页链接到新 URL 时找不到 404 URL
- reactjs - Hook 中不感兴趣的值会导致重新渲染
- javascript - 如何将标签或文本添加到动态添加的复选框?
- java - 使用 Maven 项目运行 JavaFX 时遇到问题
- python - 我不明白为什么这个函数总是返回 none
- javascript - 生成花哨/替代文本
- maven - 如何将附加参数从 maven build 传递到 npm