Reputation: 27392
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?
Upvotes: 1
Views: 6424
Reputation: 5649
I recently had the same situation. The optimum solution is to not store names in the database as full names, however, sometimes we are not in control of the data and need a solution. I ended up using the following:
SELECT * FROM db WHERE Name REGEXP " +[[:<:]]j[-'a-z]{3,}$| +[[:<:]]j[-'a-z]{3,} jr.$| +[[:<:]]j[-'a-z]{3,} sr.$";
This will search for last names starting with 'J'. I found J and S to be the most difficult because some names in the database include Jr. or Sr. at the end, throwing off the query.
I have to mention that this is a very rough solution and I can think of many instances when it would not work. It could get very long very quick. It accounts for hyphenated names or names with apostrophes, but there is no sure-fire way to match names.
A brief explanation of what is going on:
Additional cases such as II or III could also be added.
You can also use the MySQL REGEXP documentation as a reference.
Upvotes: 1
Reputation: 15443
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
Upvotes: 2
Reputation: 798556
SELECT * FROM db WHERE Name REGEX ' A[-[:alnum:]'']*$'
Upvotes: 4