I am trying to do a ‘fuzzy’ search on a sql table with names of people:
This is the table:
+----+------------+
| T1 | T2 |
+----+------------+
| 1 | Last,First |
| 2 | Last,First |
| 3 | Last,First |
+----+------------+
I want to get a select statement where I query T2 with the LIKE operator such that it works even when your query is “First Last”
The only way I can think of is by splitting the values and concatenating them and then searching again for the entry. Is there a better way to do this?
Yes, if there’s a possibility you may put both
last, firstandfirst lastinto the database, the better way is to design your schema properly.If you ever find yourself trying to search on, or otherwise manipulate, parts of columns, your schema is almost certainly broken. It will almost certainly kill performance.
The correct way is to have the table thus:
Then you can more efficiently split the user-entered name (once, before running the query) rather than trying to split every single name in the database.
In the case where the database always holds
last, first, it may not actually be necessary for a schema change.The problem you have in that case is simply one of interpreting what the user entered.
One possibility, although it is a performance killer, is to do a
likefor each separate word. So, if the user enteredpax diablo, your resultant query might be:That way, you don’t care about the order so much.
However, given my dislike of slow queries, I’d try to steer clear of that unless absolutely necessary (or your database is relatively small and likely to stay that way).
There are all sorts of ways to speed up these sorts of queries, such as:
last, firstform for searching.%something%search string as much as possible (withsomething%, indexes can still be used).