2014-01-07 20 views
-1

我有一個表格,裏面包含左右鞋的混合物,其中一些是防水的。我該如何正確排序這個MySQL表格

我需要編寫一個查詢來按字母順序對它們進行排序,但是當名稱相同時,請使用左側/右側前面的防水列。

例如

+-------------------------+------------+------------+ 
| Shoe name    | Waterproof | Left/Right | 
+-------------------------+------------+------------+ 
| boot     |  0  | left  | 
| sandal     |  0  | left  | 
| shoe     |  1  | left  | 
| boot     |  1  | left  | 
| boot     |  0  | right | 
| boot     |  1  | right | 
| sandal     |  0  | right | 
| shoe     |  1  | right | 
+-------------------------+------------+------------+ 

應歸類爲這樣的......

+-------------------------+------------+------------+ 
| Shoe name    | Waterproof | Left/Right | 
+-------------------------+------------+------------+ 
| boot     |  0  | left  | 
| boot     |  0  | right | 
| boot     |  1  | left  | 
| boot     |  1  | right | 
| sandal     |  0  | left  | 
| sandal     |  0  | right | 
| shoe     |  1  | left  | 
| shoe     |  1  | right | 
+-------------------------+------------+------------+ 

能不能做到?

+3

爲什麼左,右不是它自己的列? – Fallenreaper

+0

它可能是。這會有幫助嗎? – Urbycoz

+0

您正在存儲額外的7-8個字符與表示腳的位(1或0)。 – Fallenreaper

回答

1

但是如果涼鞋不防水呢?

在你修改的數據結構,下面應該工作:

SELECT `Shoe name`, `Waterproof`, `Left/Right` 
FROM shoe_table 
    ORDER BY CONCAT(`Shoe name`, ', ', `Waterproof`), `Left/Right`; 

您可以嘗試:通過列名

select * from shoes order by 2, 1; 

OR:

select * from shoes order by Waterproof, `Shoe name`; 
+0

嗯..沒問題。它適用於這個例子。但是如果涼鞋不防水呢?事實上,我會改變它,所以他們不會。它使問題更清楚。 – Urbycoz

0

試試這個:

ORDER BY ShoeName,Waterproof 
+0

這是行不通的。在防水左啓動之前,它將具有非防水左啓動順序。 – Urbycoz

0

這需要解析shoes列。最簡單的方法是使用substring_index()

order by substring_index(ShoeName, '(', 1), Waterproof, ShowName