所以我有三个表:tabe_1, table_2, table_3,我将使用一个字段A来映射前两个表,因为它包含在table_1和table_2中,然后用字段B和C与table_3连接,然后在上面添加一些过滤器(例如: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,有人能看看嵌套查询是怎么回事吗?谢谢。
发布于 2021-05-17 14:30:33
因为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引擎如何确定在t1.A (0)和T3.A (1)之间使用output_table中的哪个字段A与another_table连接?它不能,除非您只指定一个字段'A‘在您的子查询。
发布于 2021-05-17 17:51:21
在子查询中,t1和t2中有A列和A列,因此存在歧义。尝试列的别名,这将使事情变得简单。
发布于 2021-05-17 14:22:48
可能table_1和table_2至少有一个列存在于两个表中(您的列A)。因此,当您的子查询以select * from ...的形式执行时,它返回两个名称相同的列。如果仅执行该子查询,则不会出现问题,但不能从该子查询的结果进行查询。
将子查询重写到
select t1.A, t1.B, t1.C, t2.whatever, t3.idontknow, ...
....并确保只从一个表中选择要连接的列(或存在于mor表中的列)。
https://stackoverflow.com/questions/67571197
复制相似问题