find similarity in mysql columns - mysql

I have been asked to fetch data from Mysql-Table where Firstname and Lastname column contains similiar or alike values.
So far i have tried to use soundex expression
select * from table where soundex(firstname) = soundex(lastname)
but there are many which do not have any similarity and there are many which hasn't been found. So the gathered results are not really satisfactorily.
I have to mention, that our lastname and firstname values are mostly strong international..
Anyway, the question is: Is there an simple approach to find the rows without crafting around?

U could try:
SELECT * FROM table WHERE lastname LIKE ('%' || firstname || '%') OR firstname LIKE '%' || lastname || '%'
or something alike

Related

MySQL query with extra manual output based on WHERE

Maybe it's a dumb question, but imagine having a table with fields like:
wholename, lastname, firstname, dateOfBirth
Now I want to search that table based on user input, but I would like to give a match % to the result. Meaning:
If lastname + firstname + dateOfBirth are all found in the database matchPrct = 100.
If lastname + dataofBirth are found in the databse matchPrct = 80.
And a few other rules (With other words the field matchPrct is an auto generated field which is not really in the db).
SQL for what I would like to achieve is:
SELECT * FROM table
WHERE firstname="%mike%" AND lastname="%tysson%" AND dateOfBirth="01/01/2012"
(create matchPrct=100) OR ....
Hope what I mean is clear.
LIKE is an operator that returns a boolean value, = behaves similarly. Booleans in MySQL are 1 for true and 0 for false. That means that you can say this:
select *,
((firstname like '%mike%') + (lastname like '%tysson%') + (dateOfBirth = '01/01/2012')) / 3.0 as score
from table
where firstname like '%mike%'
or lastname like '%tysson%'
or dateOfBirth = '01/01/2012'
And then read your "how well did it match" values out of score. You can also apply individual weights to each component so that a last name match would count for more than a first name match.
In databases that don't use 1 and 0 as booleans you can cast them or use a CASE to convert booleans to the numbers you want. This doesn't apply to MySQL of course but it is worth keeping in mind.

Override column value in WHERE clause?

I was wondering if it was possible to override column value in the Where clause of a SQL query (MySQL in my case).
To be more clear, here is an example :
Suppose a basic query is :
SELECT lastname, firstname FROM contacts WHERE lastname = "Doe";
Is it possible to force lastname and firstname to return value from an other table, just by modifying what is after the WHERE part ? Something like
SELECT lastname, firstname FROM contacts WHERE lastname = (SELECT name FROM companies);
I am currently testing a web application, and I found a SQL Injection flaw where I can change Doe to whatever I want, but I'm limited with only one query (mysql_query restriction of PHP) and addslashes (so no " and ').
possible could be
SELECT lastname, firstname FROM contacts WHERE lastname = "{0}" UNION SELECT {1} --
where {0} non existed value and {1} data from other tables
UPDATE from wiki example
$res = mysql_query("SELECT author FROM news WHERE id=" . $_REQUEST['id'] ." AND author LIKE ('a%')");
become
SELECT author FROM news WHERE id=-1 UNION SELECT password FROM admin/* AND author LIKE ('a%')
The syntax that you used in your SELECT ... WHERE clause is a standard SQL feature called a subquery.
In the context of your example there is a restriction on the subquery to return just single value. Otherwise your query is a valid SQL and you can change subquery to return multiple values (with implicit OR) using IN operator like this:
SELECT lastname, firstname FROM contacts
WHERE lastname IN (
SELECT name FROM companies
);
You can dig deeper into this subject to uncover correlated subquery.

mysql SELECT * FROM table WHERE column+space+column LIKE '%query%'

For a search function, I need to be able to get the mysql function to show up results by combining two columns.
To be more precise: I have a table in the database called "members" in that there is a column called "firstname" and one called "lastname" which I need to use for this. When someone types in a whole name, eg. Jane Doe, I want the query to look whether combining firstname + a space(&nbsp?) + lastname brings forth any results.
My code so far is this:
$poster = mysql_query("SELECT id FROM members WHERE (firstname'&nbsp'lastname) LIKE '%$search%'") or die(mysql_error());
$poster = mysql_fetch_object($poster);
I know that's probably wrong, it's the most recent I've tried after trying with brackets around the firstname + lastname bits, etc, etc... But yes, any help would be greatly appreciated.
Use the CONCAT function:
SELECT id FROM members
WHERE CONCAT(firstname, ' ', lastname) LIKE ?
Try CONCAT
SELECT id FROM members WHERE concat(firstname, ' ', lastname) LIKE '%$search%'
SELECT id FROM members WHERE (firstname + ' ' + lastname) LIKE '%$search%'
I believe what you are looking for is:
$name_var = 'John Doe';
// Example 1 - using concatenation
$sql = "SELECT id FROM members WHERE CONCAT(firstname, ' ', lastname) = '$name_var'";
The above statement will search for everything where the first name is John and the last name is Doe
This is rather ineficcient as it will have to evaluate the CONCAT everytime in mysql I believe
I would reccomend validating in PHP that the string is two words as you expect e.g.
$name_var = 'John Doe';
// this will split the string based on spaces
$names = explode(' ', $name_var);
$first_name = $names[0];
$last_name = $names[1];
// Example 2 - searching each field
$sql = "SELECT id FROM members WHERE firstname = '$first_name' AND lastname = '$last_name'";
The above statement will still search for everything where the first name is John and the last name is Doe
In the above statment you are actually just searching based on the exact values so it is much more efficient. If this query is going to be ran regularly, you should also add indexes to the firstname and lastname fields in your mysql table as it will greatly increase the speed!
hope this helps!
Tom

SQL query to search in a concated string

In a database i have a table prospect and has two columns firstname and lastname.
Now the issue is that i want to search in both columns; the easy solution would be to use a query like
SELECT * FROM `prospect` WHERE lastname like '%piece of lastname%' or firstname like '%piece of firstname%'
This however requires to have two search fields, firstname and lastname. I want that users can search in one field. How should a query look like when I want to achieve this?
Do you mean you want to search the concatenation of two fields? Then you can use something like:
SELECT * FROM prospect
WHERE CONCAT(firstname,' ',lastname) LIKE '%ohn Smit%'
Is this is what you are looking for?
SELECT * FROM prospect
WHERE firstname + ' '+ lastname LIKE '%name%'

searching with a name in database for a person - MySQL

In my table I store first name in the fName column and last name in the lName column, now I need to search them with a query, but I don't know the SQL!
example
lName | fName
-----------------
Tendulkar| Sachin
Ganguly | Sourav
Khan | Zaheer
Dhoni | Mahendra Singh
The user should get MAHENDRA SINGH DHONI if he searches for Mahendra Dhoni!
select concat(fName,' ',lName) fullname
from tbl
where concat(' ',fName,' ',lName,' ') like '% Mahendra %'
and concat(' ',fName,' ',lName,' ') like '% dhoni %'
This will most certainly put to rest any hopes of a well performing query
A variation on the theme
select concat(fName,' ',lName) fullname
from tbl
where (concat(fName,' ',lName) like '%Mahendra%dhoni%'
or concat(lName,' ',fName) like '%Mahendra%dhoni%')
The 2nd version doesn't care about full part matching, e.g. dhoni will match madhonie
Both of these queries find the name correctly. Note that there are % before and after the name to match, as well as % for every space in the name.
create table tbl (fname varchar(100), lname varchar(100));
insert tbl select 'Mahendra singh', 'dhoni';
select concat(fName,' ',lName) fullname
from tbl
where (concat(fName,' ',lName) like '%Mahendra%dhoni%'
or concat(lName,' ',fName) like '%Mahendra%dhoni%');
select concat(fName,' ',lName) fullname
from tbl
where (concat(fName,' ',lName) like '%dhoni%Mahendra%'
or concat(lName,' ',fName) like '%dhoni%Mahendra%');
You are not clear on the nature of the search inputs and specifically the level of flexibility. First, is the user given two boxes for first and last name or only a single search box? If the former, then the fast solution would be:
Select concat( fname, ' ', lname)
From MyTable
Where lname Like 'dhoni%'
And fname Like 'mahendra%'
The above query only searches for where the first part of the column value begins with the search values. However, if the user can type anything into a single search box, that is harder. If it is presumed that the user has typed <name part> space <name part>, then one solution that solves that specific problem where the user enters only two words is to split on the space and run something like:
Select concat( fname, ' ', lname)
From MyTable
Where ( lname Like '%dhoni%' And fname Like '%mahendra%' )
Or ( lname Like '%mahendra%' And fname Like '%dhoni%' )
However, that query will perform awful because it forces the system to scan the entire table each time it is executed. Further, what happens when they enter a three part name like Mahendra Singh Dhoni in your search? There are simply too many edge cases for this to be workable IMO. The right solution is to get a full text indexing engine like Lucene that will create a index across both columns and rank the quality of the match.
Lucene
I'm guessing your inputs are from two different textboxes, and hopefully you are using a stored procedure :).
declare #input1 nvarchar(50)
declare #input2 nvarchar(5)
set #input1 = 'Mahendra'
set #input2 = 'Dhoni'
select upper((fname + ' ' + lname)) as 'FullName'
from customer
where fname like '%' + #input1 + '%'
or fname like '%' + #input1 + '%'
or lname like '%' + #input2 + '%'
or lname like '%' + #input2 + '%'
If you have 1 input box, you will want to split your search term by the space and loop over your search terms against fname and lname columns using the like '%term%' syntax.
Another way would be to make a stored procedure that added fname and lname together and did a soundex match. this is where you match your search term against the sound of the word in the table. Google it should help, its pretty easy.
I am assuming you have 2 inputs and you are only getting part of the first name. If this is true then the following would work:
select concat(fname, ' ', lname)
from yourtable
where substring(fname, 1, 5) = 'mahen'
and lname = 'dhoni'
The advantage of this approach is that it will use the indexes on the column(s) or a combined index whereas the like queries always do full table scans.
You might also check out a search engine like sphinx or solr when you truly do not know the data you are receiving as those are far more flexible that database queries.