Forum Moderators: open
The current syntax I have is this: SELECT * FROM table WHERE conditions ORDER BY SUBSTRING_INDEX(name, ' ', -1) direction
This works fine except if the person's last name is two words, i.e. Van Dyke. When the above command is run, the name "Van Dyke" is sorted with the "D" last names. I understand why this is doing this, but am unsure how to fix this. I am not real good with MySQL. Could someone please help me figure this out? TIA!
SELECT *
FROM table
WHERE condition(s)
ORDER by RIGHT(CHAR_LENGTH(Name) - LOCATE(' ', Name))
Unfortunately, I can't test it because I don't have MySQL. You may need to play around with using SUBSTRING() instead of RIGHT, LENGTH() instead of CHAR_LENGTH, INSTR() instead of LOCATE(). I'm not sure if you're using multibyte characters or not as well.
But essentially for 'Dick Van Dike'.
total length = 13
position of first ' ' is 5
So if you grab the rightmost 8 characters (13-5) you should get 'Van Dike'.
Another way might be to locate the first ' ' then use SUBSTRING() to get all characters to the right of the first ' ' similar to the following:
SELECT *
FROM table
WHERE condition(s)
ORDER BY SUBSTING(Name, LOCATE(' ', Name)+1).
This approach would involve only 2 function calls instead of 3.
Hope this gets you thinking on the right track. I'm sure there are many more ways to 'skin' this cat. Sorry I couldn't test it for you to give you an exact solution.
Thanks again ZydoSEO!