3

You should see what I'm trying to do here but it's not working

$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_error() returns: "improper usage of ORDER BY and UNION".

Kevin
  • 5,626
  • 3
  • 28
  • 41
Tules
  • 4,905
  • 2
  • 27
  • 29
  • A union query can normally only have an order-by clause in the LAST query being unioned, which is applied to the results of the union. Using brackets (as in Erwin's answer below) lets you order the individual queries and bypass this limitation. – Marc B Oct 03 '11 at 17:35

2 Answers2

9

Try:

$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)";

See the comments to my answer on the related question.
Or consult the fine manual.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • 1
    Also @CanSpice, doesn't each subselect require its own alias? And a `UNION ALL` will be substantially faster, esp since there can be no overlap here. – Johan Oct 03 '11 at 17:40
  • @Johan; These are not actual subselects, so they don't. I added a link to mysql docs. But good point on `UNION ALL`! – Erwin Brandstetter Oct 03 '11 at 17:50
4

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the 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)
CanSpice
  • 34,814
  • 10
  • 72
  • 86