小弟使用「select * from dh_button where type like '%mobile_banner%' order by type desc」指令後
會出現這樣的結果
請問在mysql裡面,有辦法排成
mobile_banner10
mobile_banner9
mobile_banner8
mobile_banner7
.....
mobile_banner1
嗎?
小弟目前能想到的解決辦法只能在php裡面用陣列重新排列,但總覺得mysql裡面就可以解決了,沒必要多跑好多圈
求前輩指導
<pre class="c" name="code">CREATE TABLE ithelp150302(
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
type CHAR(16) NOT NULL
);
INSERT INTO ithelp150302(type) VALUES
("mobile_banner9"),("mobile_banner8"),("mobile_banner7"),
("mobile_banner4"),("mobile_banner5"),("mobile_banner6"),
("mobile_banner3"),("mobile_banner2"),("mobile_banner1"),
("mobile_banner10");
SELECT *
FROM ithelp150302
ORDER BY CAST(SUBSTRING(type FROM 14) AS UNSIGNED) DESC;
+----+-----------------+
| id | type |
+----+-----------------+
| 10 | mobile_banner10 |
| 1 | mobile_banner9 |
| 2 | mobile_banner8 |
| 3 | mobile_banner7 |
| 6 | mobile_banner6 |
| 5 | mobile_banner5 |
| 4 | mobile_banner4 |
| 7 | mobile_banner3 |
| 8 | mobile_banner2 |
| 9 | mobile_banner1 |
+----+-----------------+
基本上,type欄位中,mobile_banner10,比對到『1』的時候,它比9小,所以
反向排序,自然會被排到9的後面
或許,你可以試試這麼寫:
<pre class="c" name="code">
select * from dh_button where type like '%mobile_banner%' order by CHAR_LENGTH(type) desc,type desc
先依據欄位內容長度排序,再依欄位排序
手邊沒有MySql,所以沒測試過,請自行測試~~
考慮直接讓他變成兩位數,如何?
mobile_banner01
mobile_banner02
.....
...
..
<pre class="c" name="code">select * from dh_button where type like '%mobile_banner%' order by CONVERT(REPLACE (type, 'mobile_banner', ''),UNSIGNED INTEGER) desc