UNION和ORDER BY的结果很奇怪 [英] Weird result with UNION and ORDER BY
问题描述
我有这个查询(简体):
I have this query (simplified):
SELECT score FROM tbl WHERE id = xx ORDER BY score DESC;
它可以正常工作.现在,我向该查询添加一个像这样的UNION
:
And it works correctly. Now I add to this query an UNION
like this:
(SELECT score FROM tbl WHERE id = x ORDER BY score DESC)
UNION
(SELECT score FROM tbl WHERE id = y)
现在,第一个查询的所有第一个结果集都被弄乱了,不遵守ORDER BY score DESC
Now all the first result-set of the first query is messed up not respecting the ORDER BY score DESC
推荐答案
从tbl中选择分数,id = x 联盟 从tbl WHERE id = y中选择分数
SELECT score FROM tbl WHERE id = x UNION SELECT score FROM tbl WHERE id = y
按分数DESC排序;
ORDER BY score DESC;
只需在末尾添加订单即可.它将应用于整个结果集.如果要区分结果,请添加订单栏,如下所示:
just add the order by to the end. it will apply to the entire result set. If you want to differentiate the result add an order col like so:
选择1作为order_col,在tbl WHERE id = x时得分 联盟 选择2作为order_col,从tbl WHERE id = y得分
SELECT 1 as order_col, score FROM tbl WHERE id = x UNION SELECT 2 as order_col, score FROM tbl WHERE id = y
ORDER BY order_col,得分DESC;
ORDER BY order_col ,score DESC;
这篇关于UNION和ORDER BY的结果很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!