21

Here is my query

(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only three doors%" OR `joke` LIKE "%only three doors%") ORDER BY `ups` DESC,`downs` ASC)
UNION
(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only%" OR `joke` LIKE "%only%") ORDER BY `ups` DESC,`downs` ASC)
UNION
(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%three%" OR `joke` LIKE "%three%") ORDER BY `ups` DESC,`downs` ASC)
UNION
(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%doors%" OR `joke` LIKE "%doors%") ORDER BY `ups` DESC,`downs` ASC)
 LIMIT 0, 30

For some reason it doesn't seem to order by ups or downs...it just tosses me back the results in the order they are naturally in the database.

When I cut it down to only one query, it works fine, but other than that, it seems to ignore it.

I also don't want to order by the entire results, or I would have put LIMIT 0,30 Order By blah

5 Answers 5

30

From MySQL documentation:

... use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.

Basically the only time an ORDER in a union will be useful is if you are using LIMIT as well.

So if you query was like this:

(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only three doors%" OR `joke` LIKE "%only three doors%") ORDER BY `ups` DESC,`downs` ASC LIMIT 10)
UNION ...

Then you would see the first ten records that would be returned based on that order, but they wouldn't necessarily be displayed in order.

UPDATE:

Try this -

(SELECT *, 1 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only three doors%" OR `joke` LIKE "%only three doors%") )
UNION
(SELECT *, 2 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only%" OR `joke` LIKE "%only%") )
UNION
(SELECT *, 3 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%three%" OR `joke` LIKE "%three%") )
UNION
(SELECT *, 4 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%doors%" OR `joke` LIKE "%doors%"))
 ORDER BY `ob`, `ups` DESC,`downs` ASC LIMIT 0, 30
10
  • 2
    Do you have any ideas on how to make it work the way that I would like it to? Essentially I want to combine the different queries, and have each one individually sorted by there ups and downs, then combined, one after another. Dec 30, 2011 at 23:58
  • So the first query sorted, then the second sorted. If the first is greater than 30, then it would only show the first 30 in the first query. Dec 30, 2011 at 23:59
  • Bleh, that's a tough one. You're saying you don't want to sort the entire set correct? Just append one sorted set to the end of another and take the first 30? Dec 31, 2011 at 0:03
  • That's correct. There is paging so when someone goes to the next page i'll limit 30,60 etc. Dec 31, 2011 at 0:05
  • 2
    That is strange. Why would MySQL every want to randomly order an ordered list when concatenating?
    – Jonathon
    Aug 16, 2013 at 1:38
4

I got solution for this:

SELECT *
FROM (
    (SELECT 1 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE city=".$city." AND region=".$region." AND cantone=".$cantone.")
     UNION
    (SELECT 2 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE region=".$region." AND cantone=".$cantone.")
    union all
    (SELECT 3 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE cantone=".$cantone.")
) As u
GROUP BY uid 
ORDER BY SortRank,state=2, title ASC
LIMIT 0,10

In above query i want result eg. first show all records with city, region and cantone then if city not available then show all records with region and cantone and then all records with cantone of city. So, removing repeating records i used GROUP BY clause, it will sort all records based on query group then all records with state=2.

2
  • Thank you! I was spending hours trying to figure this out. Mar 19, 2017 at 13:44
  • GROUP BY uid is not guaranteed to return a specific row. You are relying on undocumented behavior that it return the first one in which it appears. That is, there is no guarantee that if a uid appears in both SortRank 1 and SortRank 2, that it will still have SortRank 1 after the group by. Apr 24, 2019 at 21:52
3

What the query does, is to order each sub-query separately and unifying all of them. There is no guarantee the result would be ordered.

what you need to do is to order the unified query as such:

Select * from (
  (SELECT *, 1 as `p` FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only three doors%" OR `joke` LIKE "%only three doors%"))
  UNION
  (SELECT *, 2 as `p` FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only%" OR `joke` LIKE "%only%"))
  UNION
   (SELECT *, 3 as `p` FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%three%" OR `joke` LIKE  "%three%"))
  UNION
  (SELECT *, 4 as `p` FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%doors%" OR `joke` LIKE "%doors%"))
    ) ORDER BY `p` ASC, `ups` DESC,`downs` ASC
4
  • I had thought about that, but as I mentioned above, that's not the result i'm looking for. All results from the first query should always come before any from the second. Dec 31, 2011 at 0:01
  • 1
    I edited the query to fit your needs (added an additional field 'p')
    – Uri Goren
    Dec 31, 2011 at 0:07
  • 1
    I'd give it to you, but the other guy had the correct solution first. Thanks though Dec 31, 2011 at 0:10
  • Another thing with this query, surrounding the whole thing in a Select * FROM actually returns no results Dec 31, 2011 at 0:26
1

You should be able to use UNION ALL to remove duplicate removal (and also complete result set sorting). Using that the result set should be in the order of the select statements in the query.

4
  • So just replace UNION with UNION ALL? Dec 31, 2011 at 0:14
  • Try it, see if it helps, if not, i wasted not more than 20 seconds of your time :) .. (i don't have a local mysql handy to test it out, but it should make a difference)
    – cairnz
    Dec 31, 2011 at 0:15
  • wait, I don't want duplicates. Dec 31, 2011 at 0:16
  • Then stick with adding the additional column to sort by, as in the answer already accepted.
    – cairnz
    Dec 31, 2011 at 0:18
0

Maybe this is a bit unrelated to the question, but for those who want union two queries or more ordered by different columns:

Since there is no way you could use one order by statement because the columns in both queries are not the same, you might consider adding "fake" columns to make the number of columns equal in both queries, this is my answer to an excerise on HackerRank similar to the question asked here

WITH sub AS 
(
(SELECT CONCAT(Name , "(" , SUBSTRING(OCCUPATION,1,1) , ")") as first , Name , OCCUPATION , -1 as counts FROM OCCUPATIONS)
UNION ALL
(SELECT CONCAT("There are a total of " , COUNT(OCCUPATION) , " " , LOWER(OCCUPATION) , "s" , ".") as first , "z" as Name , OCCUPATION , COUNT(OCCUPATION) as counts FROM OCCUPATIONS
GROUP BY OCCUPATION)
)

SELECT first FROM sub
ORDER BY Name ASC , counts ASC , OCCUPATION ASC

Note : You should choose the appropriate values for the fake columns to get yours rows in the correct position (notice -1 as counts FROM OCCUPATIONS , "z" as Name in my query)

I initially misunderstood the question on HackerRank as it did not require me to union the two queries but i ended up learning something new anyways , hope that was helpful (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.