I want to use order by with union in mysql query. I am fetching different types of record based on different criteria from a table based on distance for a search on my site. The first select query returns data related to the exact place search . The 2nd select query returns data related to distance within 5 kms from the place searched. The 3rd select query returns data related to distance within 5-15 kms from the place searched.
Then i m using union to merge all results and show on a page with paging. Under appropriate heading as 'Exact search results', 'Results within 5 kms' etc
Now i want to sort results based on id or add_date. But when i add order by clause at the end of my query ( query1 union query 2 union query 3 order by add_date). It sorts all results. But what i want is it should sort under each heading.
You can use subqueries to do this:
I got this working on a join plus union.
I tried adding the order by to each of the queries prior to unioning like
but it didn't seem to work. It didn't actually do the ordering within the rows from each select.
I think you will need to keep the order by on the outside and add the columns in the where clause to the order by, something like
This may be a little tricky, since you want to group by ranges, but I think it should be doable.
You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:
Try:
Where [QUERY 1] and [QUERY 2] are your two queries that you want to merge.