How can I sequence this MySQL table correctly

65 views Asked by At

I've got a table containing a mixture of left and right shoes, some of which are waterproof.

I need to write a query to sort them alphabetically, but- when the name is the same- use the waterproof column ahead of left/right.

e.g.

+-------------------------+------------+------------+
| 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    |
+-------------------------+------------+------------+

Should be sorted as such...

+-------------------------+------------+------------+
| 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    |
+-------------------------+------------+------------+

Can it be done?

3

There are 3 answers

1
Ravinder Reddy On BEST ANSWER

But what if the sandals were not waterproof?

On your modified data structure, the following should work:

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

You can try:

select * from shoes order by 2, 1;

OR by column name:

select * from shoes order by Waterproof, `Shoe name`;
1
BWS On

Try this:

ORDER BY ShoeName,Waterproof 
0
Gordon Linoff On

This requires parsing the shoes column. The easiest way is using substring_index():

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