请查看以下查询:
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)
这是查询应该做的事情:
我收到错误:
Error Code: 1221. Incorrect usage of UNION and ORDER BY
示例数据集:
感谢任何帮助。
答案 0 :(得分:0)
对每个单独的查询使用UNION
或LIMIT
的{{1}}个查询时,您需要使用括号来组织查询,例如
ORDER BY
您可以编写上述查询以避免此错误
(query 1 with limit order by )
UNION
(query 1 with limit order by )
答案 1 :(得分:0)
您需要在第一个查询中使用ORDER BY
和LIMIT
的子查询。
这样的事情:
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结果