申请"ORDER BY"在"UNION"上(MySQL的) [英] apply "ORDER BY" on a "UNION" (Mysql)
问题描述
美好的一天. 所以,每个标题都在标题中:)
Good Day. So, everythign is in the title :)
我正在寻求合并两个请求的结果,并将结果排序在一起(因为彼此之间不是一个接一个). =>我正在考虑应用工会并命令他们. 它没有用.
I am looking to merge the result of two requests and order the result together (as in not one after the other). => I was thinking of applying an union and order them. It didn't worked.
我在这里在堆栈上或在这里 developpez(!!法国网站).我尝试不同的示例和建议,但没有成功. 从我的观点看来,这是因为我正在使用Mysql.
I looked around like here on Stack or here developpez (!!french website). I try the different exemple, and suggestion, but no success. It seems from what i red that it's because I am working on Mysql.
无论如何,这是我的尝试,以及结果:
Anyway, here are my attemps, and the results:
我原来的2个请求
SELECT * FROM user_relation WHERE from_user_id = 1
List item
SELECT * FROM user_relation WHERE to_user_id = 1
此列表的结果是首先选择的结果(由索引键表示),然后是由索引KEy排序的第二选择的结果.
this result of a list made of the result of teh frist select (odered by index key) followed by the result of 2nd select ordered by Index KEy.
尝试1:
(SELECT * FROM user_relation WHERE from_user_id = 1 ORDER BY trust_degree)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1 ORDER BY trust_degree)
请求已执行,但结果与原始请求相同:第一个选择的结果(按索引键排序),然后是第二个请求的结果
The request ran, but teh result were teh same as orginal request: result of first select (order by index Key) followed by the results of the second request
尝试2:
(SELECT * FROM user_relation WHERE from_user_id = 1 ORDER BY trust_degree)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1 ORDER BY trust_degree)
ORDER BY trust_degree
=>请求已运行,结果为尝试1,但在Mysql逻辑中发出警告: (这种关闭类型已经过分析(ORDER BY))
=> request ran, result as attempt 1, but with a warning i the Mysql logic: (this type of close has been already analyzed (ORDER BY))
尝试3
(SELECT * FROM user_relation WHERE from_user_id = 1
UNION
SELECT * FROM user_relation WHERE to_user_id = 1)
ORDER BY trust_degree
=>不运行,但出现错误#1064-UNION附近的语法错误
=> Do not ran, but an error #1064 - syntax error near UNION
尝试4:
SELECT *
FROM (
(SELECT * FROM user_relation WHERE from_user_id = 1)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1)
)
ORDER BY trust_degree
=>不运行,并且列出了6条错误. 有什么建议吗?
=> do not ran, and a nice list of 6 error. Any suggestion?
推荐答案
SELECT *
FROM (
(SELECT * FROM user_relation WHERE from_user_id = 1)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1)
) AS i
ORDER BY trust_degree
您必须为您的选择分配一个别名.但是在这种情况下,UNION
不是必需的,可以用简单的OR
代替,正如@Karoly Horvath在其评论中指出的那样.结果查询如下:
You have to assign an alias to your select. But in this case a UNION
is not necessary and could be replaced by a simple OR
, as @Karoly Horvath points out in his comment. The resulting query would look like this:
SELECT
*
FROM user_relation
WHERE from_user_id = 1 OR to_user_id = 1
ORDER BY trust_degree
这篇关于申请"ORDER BY"在"UNION"上(MySQL的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!