mysql - 我在查询 SQL (UNION ALL) 中哪里出错了?

标签 mysql sql

我尝试使用UNION ALL,但出现错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') GROUP BY Product_id' at line 13

如何为 UNION 表和结果 GROUP BY 设置正确的别名?

示例:sqlfiddle

最佳答案

这是正确的查询结构,UNION/ALL 不需要别名,但派生表需要。

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;

关于mysql - 我在查询 SQL (UNION ALL) 中哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48102462/

相关文章:

php - MySQL在单个单元格中通过多个ID进行连接查询

javascript - 在 PHP 中单击复选框时更新状态

php - 对我的 MySQL 表运行更新,将 1 个字段的内容替换为另一个字段的内容

c++ - SQL结构与C++ STL映射

sql - 在 Hive 中将字符串转换为时间戳

mysql - 使用 mysqldump 忽略一张表?

sql - 按 60 分钟滑动窗口分组

mysql - 是否只有在所有匹配行都将更新时才可以更新 mysql 表?

sql四舍五入到5的倍数?

MySQL VIEW 在 where 语句中具有变形类型