简体   繁体   中英

MySQL ORDER BY Another table's column names

I have one table with items for an order that looks like this:

Product | Color | Size | Size Range ID (from a different, joined table)
-----------------------------------------------------------------------
Shirt   | Blue  |  L   |   1
Shirt   | Blue  |  M   |   1
Shirt   | Blue  |  S   |   1

Note that the sizes are sorted in alphabetical order in the table above.

I also have a size ranges table that looks like this:

id | size_01 | size_02 | size_03
--------------------------------
 1 |    S    |   M     |   L  

How can I force the items on the first table to ORDER BY the position of the size in the second table?

You can use join to combine the tables and then field() to get the position in the column list:

select i.*
from items i left outer join
     SizeRange sr
     on i.SizeRangeId = sr.SizeRangeId
order by field(i.Size, sr.size_01, sr.size_02, sr.size_03)
SELECT
  MAX(CASE Size WHEN 'S' THEN Size ELSE '' END) AS 'size_01',
  MAX(CASE Size WHEN 'L' THEN Size ELSE '' END) AS 'size_02',
  MAX(CASE Size WHEN 'M' THEN Size ELSE '' END) AS 'size_03'
FROM Test
GROUP BY Product

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