MySQL:使用ORDER BY和UNION

时间:2014-04-15 15:58:56

标签: mysql e-commerce opencart mysql-workbench

请查看以下查询:

INSERT INTO product_filter (product_id,filter_id)
SELECT product_id,
(CASE WHEN price < 100 then 1
WHEN price >= 100 AND price < 500 then 2
WHEN price >= 500 AND price < 1000 then 3
WHEN price >= 1000 AND price < 1500 then 4
WHEN price >= 1500 AND price < 2000 then 5
WHEN price >= 2000 AND price < 2500 then 50
WHEN price >= 2500 AND price < 3000 then 6
ELSE 51 END) AS filter_id
FROM product_special
ORDER BY priority DESC, date_end DESC
LIMIT 1
UNION
SELECT product_id,
(CASE WHEN price < 100 then 1
WHEN price >= 100 AND price < 500 then 2
WHEN price >= 500 AND price < 1000 then 3
WHEN price >= 1000 AND price < 1500 then 4
WHEN price >= 1500 AND price < 2000 then 5
WHEN price >= 2000 AND price < 2500 then 50
WHEN price >= 2500 AND price < 3000 then 6
ELSE 51 END) AS filter_id
FROM product WHERE product_id not IN
(SELECT product_id FROM product_special)

这是查询应该做的事情:

  • 从product_special表中选择所有特殊价格,并根据价格将它们与不同的价格过滤器相关联
  • 每个产品都可以有多个特价,所以只需选择优先级较高且价格较长的产品
  • 从产品表中选择所有常规价格(仅限于product_special表中没有特殊价格的价格)并根据价格将它们与不同的价格过滤器相关联

我收到错误:

Error Code: 1221. Incorrect usage of UNION and ORDER BY

示例数据集:

Products

Specials

感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

对每个单独的查询使用UNIONLIMIT的{​​{1}}个查询时,您需要使用括号来组织查询,例如

ORDER BY

您可以编写上述查询以避免此错误

(query 1 with limit order by ) 
 UNION 
(query 1 with limit order by )

答案 1 :(得分:0)

您需要在第一个查询中使用ORDER BYLIMIT的子查询。

这样的事情:

INSERT INTO product_filter (product_id,filter_id)
SELECT * FROM
(SELECT product_id,
(CASE WHEN price < 100 then 1
WHEN price >= 100 AND price < 500 then 2
WHEN price >= 500 AND price < 1000 then 3
WHEN price >= 1000 AND price < 1500 then 4
WHEN price >= 1500 AND price < 2000 then 5
WHEN price >= 2000 AND price < 2500 then 50
WHEN price >= 2500 AND price < 3000 then 6
ELSE 51 END) AS filter_id
FROM product_special
ORDER BY priority DESC, date_end DESC
LIMIT 1) a
UNION
SELECT product_id,
(CASE WHEN price < 100 then 1
WHEN price >= 100 AND price < 500 then 2
WHEN price >= 500 AND price < 1000 then 3
WHEN price >= 1000 AND price < 1500 then 4
WHEN price >= 1500 AND price < 2000 then 5
WHEN price >= 2000 AND price < 2500 then 50
WHEN price >= 2500 AND price < 3000 then 6
ELSE 51 END) AS filter_id
FROM product WHERE product_id not IN
(SELECT product_id FROM product_special)

答案 2 :(得分:0)

您应该使用圆括号来对单个查询使用ORDER / LIMIT

例如

(SELECT * FROM table1 WHERE ... ORDER BY field1 LIMIT 0, 1)
UNION   
(SELECT * FROM table1 WHERE ...)

如果在括号外使用Order BY,则它适用于UNIONED结果