我尝试使用UNION ALL
,但收到了错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 靠近')GROUP BY Product_id'在第13行
如何为UNION表和结果GROUP BY设置正确的别名?
示例答案 0 :(得分:0)
这是正确的查询结构,UNION / ALL不需要别名,但Derived表会。
SELECT
Product_id,
sum(Total) as sumOfTotal
FROM ((SELECT
b.Products_idProducts AS Product_id,
COUNT(b.Products_idProducts) AS Total
FROM products_has_colors a
RIGHT JOIN products_has_colors b
ON a.Colors_idColors = b.Colors_idColors
AND b.Products_idProducts <> a.Products_idProducts
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts)
UNION ALL
(SELECT
b.Products_idProducts AS Product_id,
COUNT(b.Products_idProducts) AS Total
FROM Products_has_ProductComposition a
RIGHT JOIN Products_has_ProductComposition b
ON (a.CompositionId = b.CompositionId
AND b.Products_idProducts <> a.Products_idProducts)
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts)) mytable
GROUP BY Product_id;
答案 1 :(得分:0)
你的别名是错误的,你有一些你不需要的括号。
您需要为整个UNION
查询设置别名,如下所示:
SELECT product_ID
FROM (
SELECT BLAH
UNION
SELECT BLAH2
) as t1
GROUP BY product_ID;
在你的情况下应该是这样的:
SELECT Product_id
FROM (
SELECT b.Products_idProducts AS Product_id, COUNT(b.Products_idProducts) AS Total
FROM products_has_colors a
RIGHT JOIN products_has_colors b
ON a.Colors_idColors = b.Colors_idColors AND b.Products_idProducts <> a.Products_idProducts
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts
UNION ALL
SELECT b.Products_idProducts AS Product_id, COUNT(b.Products_idProducts) AS Total
FROM Products_has_ProductComposition a
RIGHT JOIN Products_has_ProductComposition b
ON (a.CompositionId = b.CompositionId AND b.Products_idProducts <> a.Products_idProducts)
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts
) as t1
GROUP BY Product_id;
答案 2 :(得分:0)
表名别名(t1)的错误positioon
SELECT Product_id FROM (
(SELECT
b.Products_idProducts AS Product_id
, COUNT(b.Products_idProducts) AS Total
FROM products_has_colors a
RIGHT JOIN products_has_colors b ON a.Colors_idColors = b.Colors_idColors
AND b.Products_idProducts <> a.Products_idProducts
WHERE a.Products_idProducts = 1
GROUP BY b.Products_idProducts)
UNION ALL
(SELECT
b.Products_idProducts AS Product_id
, COUNT(b.Products_idProducts) AS Total
FROM Products_has_ProductComposition a
RIGHT JOIN Products_has_ProductComposition b ON a.CompositionId = b.CompositionId
AND b.Products_idProducts <> a.Products_idProducts
WHERE a.Products_idProducts = 1 GROUP BY b.Products_idProducts)
GROUP BY Product_id) t1