I have a MySQL database with a field Name which contains full names. To select all people with last names starting with a particular letter, let's say A for this example, I use the following query: SELECT * FROM db WHERE Name LIKE '% A%'
. However, this also selects users who have a middle name starting with A. Is there anyway to alter this query so that only a last name starting in A will be selected?
views:
57answers:
2
+4
A:
SELECT * FROM db WHERE Name REGEX ' A[-[:alnum:]'']*$'
Ignacio Vazquez-Abrams
2010-03-11 05:46:19
+1
A:
Ignacio's Regex works and is a lot more flexible - you could also use something like this if Regex completely confuses you:
SELECT * FROM db WHERE LEFT(SUBSTRING_INDEX(Name, ' ', -1), 1) = 'A'
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html
AvatarKava
2010-03-11 05:49:23
Possible shortcoming here is last names with spaces, eg. "Van Buren" - but I presume you probably don't have a good way of differentiating middle and last names anyhow in this type of field.
AvatarKava
2010-03-11 05:51:53