Forum Moderators: open

Message Too Old, No Replies

How to handle MySQL sorting of names

         

JRNeher

9:52 pm on Aug 23, 2008 (gmt 0)

10+ Year Member



I have a MySQL statement within a php page that sorts a list of names by last name.

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!

ZydoSEO

5:42 pm on Aug 24, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have mainly Oracle and MS*SQL experience, no MySQL, but looking at the docs online for string functions you should be able to use LOCATE() or INSTR() to do this. Look for the first occurance of a substring of ' ' in Name (assuming you only have first and last name - no middle names - and you always have at least 1 space in the name and name is of format 'firstname lastname') and then sort on everything to the right of the first space similar to:

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.

JRNeher

6:34 pm on Aug 24, 2008 (gmt 0)

10+ Year Member



Thank you so much for your reply ZydoSEO. The second option that you suggested appears to work wonderfully. I did not have a chance to try the first option you gave, but for anyone else that might stumble across this situation, "Van Dyke" is sorted where it should be (with the "V"s) using:
SELECT *
FROM table
WHERE condition(s)
ORDER BY SUBSTING(Name, LOCATE(' ', Name)+1).

Thanks again ZydoSEO!