Mysql Order by last name when full name for column

自作多情 提交于 2019-12-10 13:42:46

问题


I have the following:

 SELECT * FROM users LEFT JOIN user_info ON users.id=user_info.user_id 
                WHERE 
                    ((user_info.tester != 1) OR (user_info.tester is null)) AND 
                    id in (SELECT explicituser_id FROM user_login WHERE (created < '2012-12-17' OR created >= date_add('2012-12-17', interval 1 day))) AND 
                    id IN (SELECT participte_id FROM roster WHERE roster_id IN (6)) 
                order by 
                    substring_index(users.name, ' ', -1)

I'm simply trying to sort by the users' last name.

However, while it can sort by the first name, the last name is buggy. If the user has quotes around their name (ie. "Abigail Martinez" it will make the sorting incorrect. If the user provides only one name, and it's a nickname (ie. Juan), then it will also make it incorrect. And then there's middle initials (ie. Tiffany S Villa or Steve de la Makinov). Unfortunately, this uses only one column for the full name (users.name).

Any help is appreciated. Thanks!


回答1:


substring_index(TRIM(users.name), ' ', -1) Adding TRIM will remove trailing spaces. After that, sorting occurs as expected.




回答2:


if it is the case try to get all the rows and then may try with mysql_real_escape_string. so that you will not be having quotes. it'll be something like this.

 $row['new_name'] = mysql_real_escape_string($row['name']);

I'm not too sure performance wise whether its good to go for it or not..

Hope this may helps



来源:https://stackoverflow.com/questions/13919441/mysql-order-by-last-name-when-full-name-for-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!