I have color
column in MySQL table which type is ENUM('RED', 'YELLOW', 'MY_COLOR', 'BLACK')
, and another name
column which type is VARCHAR(30)
.
I would like to get all table rows in the following order:
YELLOW
rows first, sorted by name
RED
rows last, sorted by name
name
Is that possible to make this kind of sort in 1 query ?
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
If you just create a list of the enum values (instead of strings) via parsing, then sort that list using Collections. sort , it should sort the way you want. If you need a list of strings again, you can just convert back by calling name() on each element.
$syntax = mysql_query("SELECT COLUMN_TYPY FROM information_schema. `COLUMNS` WHERE TABLE_NAME = '$table' AND COLUMN_NAME ='$colm'"); if (! mysql_error()){ //Get a array possible values from table and colm.
Use:
ORDER BY CASE color
WHEN 'YELLOW' THEN 1
WHEN 'RED' THEN 3
ELSE 2
END, name
This works fine with mysql. But for h2 DB it throws an error
Caused by: org.h2.jdbc.JdbcSQLException: Order by expression "CASEWHEN((color = 'YELLOW'), 1, CASEWHEN((color = 'RED'),3))" must be in the result list in this case; SQL statement:
To avoid the error add the stmt CASEWHEN((color = 'YELLOW'), 1, CASEWHEN((color = 'RED'),3))
in the select clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With