简体   繁体   中英

MySQL order by X but sort two of Y first

Ok, hoping someone has an elegant solution for this. I've been doing it in two queries, and thought it might be done in one.

Sample Data:

ID, Area, AgentID, Price
1, AZ1, 15, 100
2, AZ1, 16, 110
3, AZ2, 15, 180
4, AZ1, 12, 109
5, AZ3, 15, 180
6, AZ1, 11, 90
7, AZ2, 15, 140
8, AZ1, 10, 110
9, AZ4, 11, 120
10, AZ1, 12, 130

The basic idea of the query is that I need to get everything (SELECT *) from the data where the Area is AZ1, sorting by Price Decending. Very basic: SELECT * FROM data WHERE Area=AZ1 ORDER BY Price DESC

But, I need two entries with AgentID=15 to be sorted first. I've previously been doing this as two queries:

SELECT * FROM data WHERE Area=AZ1 AND AgentID=15 ORDER BY Price DESC LIMIT 2

SELECT * FROM data WHERE Area=AZ1 ORDER BY Price DESC

and just displaying the first result first. It's not been a big deal to do it this way, but in honor of making things sleek and sexy, can I combine these? When I tried a subquery, it said that "This version of MySQL doesn't yet support LIMIT...etc subqueries"

It would also be nice to not have to sort out the repeat results through PHP (I was using array_diff), plus it makes for non-nice pagination fixes (offsets minus 2, etc) in URL Routing.

Also, if this is the best way to do this memory/speed/whatever-wise, feel free to say that, too! (Though I doubt it is).

Thanks!

You can do this with a union all :

select t.*
from ((SELECT *, ord = 1 FROM data WHERE Area=AZ1 AND AgentID=15 ORDER BY Price DESC LIMIT 2)
      union all
      (SELECT *, ord = 2 FROM data WHERE Area=AZ1 )
     ) t
order by ord, price desc

Just to have a variation on the same theme, you could use IF(...) too:

SELECT * FROM data 
WHERE Area = 'AZ1' 
ORDER BY IF(AgentID = 15, 1, 2)
         Price DESC

If you want the row having AgentID = 15 appear on the top and at their "normal" position try that:

SELECT * FROM (
  SELECT *, 1 AS ord FROM data WHERE AgentID = 15 AND Area=AZ1
  UNION SELECT *, 2 AS ord FROM data WHERE Area=AZ1
) AS S
ORDER BY S.ord, S.Price DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM