Frage

I have a table in a MySQL database which contains data like this;

ID  text
1   Action Jackson
2   The impaler
3   The chubby conquistador
4   Cornholer

I want to display them in alphabetical order minus the leading "The ". This is what I've come up with which works.

SELECT ID, CASE LEFT(l.text, 4) WHEN "The " THEN CONCAT(RIGHT(l.text, LENGTH(l.text) - 4), ", The") ELSE l.text END AS "word"
FROM list l

This solution seems a little clunky, does anyone have a more elegant answer?

War es hilfreich?

Lösung

I think this is what you are looking for:

SELECT ID,
       text
FROM list l
ORDER BY TRIM(LEADING 'The ' FROM text);

Andere Tipps

If you can at all, I would think of restructuring your data a bit.. Its hundreds of times better to rely on mysql indexes and proper sorting instead of doing it dynamically like this.

How about adding a field that drops the 'The ', and sort on that? You could make sure that this secondary field is always correct with a few triggers.

SELECT TRIM(LEADING 'The' FROM text) as word 
FROM list 
ORDER BY TRIM(LEADING 'The' FROM text)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top