Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL中的联合和按问题排序_Mysql_Sql_Sql Order By_Union - Fatal编程技术网

MySQL中的联合和按问题排序

MySQL中的联合和按问题排序,mysql,sql,sql-order-by,union,Mysql,Sql,Sql Order By,Union,你应该看看我在这里想做什么,但它不起作用 $getquery = "SELECT * FROM highscore WHERE score >= '$score' ORDER BY score ASC LIMIT 6 UNION SELECT * FROM highscore WHERE score < '$score' ORDER BY score DESC LIMIT 5"; mysql\u错误返回:ORDER BY和UNION使用不当。请尝试: $getquery

你应该看看我在这里想做什么,但它不起作用

$getquery = "SELECT * 
FROM highscore 
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 6

UNION

SELECT * 
FROM highscore 
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5";
mysql\u错误返回:ORDER BY和UNION使用不当。

请尝试:

$getquery = "(SELECT * 
FROM highscore 
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 6)

UNION ALL -- guaranteed to be beneficial in this case as Johan commented

(SELECT * 
FROM highscore 
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5)";
看。
或。

若要对单个SELECT应用ORDER BY或LIMIT,请将子句放在包含SELECT的括号内:

(SELECT * 
 FROM highscore 
 WHERE score >= '$score'
 ORDER BY score ASC
 LIMIT 6)

UNION

(SELECT * 
 FROM highscore 
 WHERE score < '$score'
 ORDER BY score DESC
 LIMIT 5)

联合查询通常只能在最后一个被联合的查询中具有order by子句,该子句应用于联合的结果。在Erwin的回答中使用括号可以让您对单个查询进行排序并绕过此限制。另外@CanSpice,每个子选择是否都需要自己的别名?而且一个联盟将大大加快,特别是因为这里没有重叠。@Johan;这些不是实际的子选择,所以它们不是。我添加了mysql文档的链接。但这一点很好!