我正在使用此查询来计算使用union和查询末尾的别名从2个表生成的行,但它不起作用:
SELECT COUNT(*) FROM (
(SELECT * FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN new_cards
WHERE new_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND new_cards.`Sup_ID` = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND new_cards.`Bill_ID` = bills.`Bill_ID`)
UNION
(SELECT * FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN sold_cards WHERE
sold_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND sold_cards.`Sup_ID` = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND sold_cards.`Bill_ID` = bills.`Bill_ID`)
) w
错误是
Error Code: 1060
Duplicate column name 'Cat_ID'
答案 0 :(得分:2)
似乎在猫和账单表中都有一个名为Cat_ID的列。当您对表上的连接执行select *时,您将获得重复的列名称。
一些可能的解决方案:
答案 1 :(得分:1)
这些不是变量,可以连接或联合具有重复列名的表。见下文。
错误是来自联盟还是加入?尝试只运行第一个子选择,然后只运行第二个子选择。
作为一种可能的解决方法,看起来您可以将两张牌桌的联合分解出来,SELECT FROM bills JOIN cats JOIN suppliers JOIN (SELECT * from new_cards UNION SELECT * from sold_cards) cards WHERE ...
UNION合并重复的行(UNION ALL返回两侧的所有行)。如果你知道你不会有重复,你可以完全避免联合并直接选择两个计数的总和,即select (select count(*) from ...joins...) + (select count(*) from ...joins...)
。
这些都不能解释为什么它会返回错误。
我进行了快速测试,结果如下:
create table a (id int, a int, b int);
create table b (id int, a int, b int);
insert into a values (1,1,1), (2,2,2);
insert into b values (3,3,3);
select count(*) from ( (select * from a) union (select * from b) ) t;
+----------+
| count(*) |
+----------+
| 3 |
+----------+
1 row in set (0.00 sec)
select * from ( (select * from a) union (select * from b) ) t;
+------+------+------+
| id | a | b |
+------+------+------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
+------+------+------+
3 rows in set (0.00 sec)
select count(*) from a inner join b where a.a = b.a and b.a = a.a;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
答案 2 :(得分:1)
哦,我明白了 - 错误来自嵌套的选择临时表。
运行查询时,mysql必须为两个内部选择中的每一个创建一个临时表。这些临时表出错,因为您无法创建具有两个相同名称列的表。
如果你将两个Cat_ID等同于连接条件而不是WHERE,那么mysql应该认识到它们是相同的并且应该可以工作;类似的东西:
SELECT COUNT(*) FROM (
SELECT * FROM bills
JOIN cats USING (Cat_ID)
JOIN suppliers USING (Sup_ID)
JOIN sold_cards USING (Bill_ID, Sup_ID)
UNION
SELECT * ...
)
或者像Svea所说,选择像cats.Cat_ID这样的特定列来计算。 (选择一列只比选择所有列运行得快)
select * from (select * from a join b) t;
ERROR 1060 (42S21): Duplicate column name 'id'
select * from (select * from a join b using (id, a, b)) t;
Empty set (0.00 sec)