This question already has an answer here:
I have 3 tables
Table 1- Users:
_______________________
|uid | uname |
|______|______________|
| 1 | John99 |
| 2 | Steve12 |
| 3 | Smith_a |
| 4 | Robert.t |
| 5 | Williams.a |
|______|______________|
Table 2-Firstname:
_____________________
|eid | fname |
|______|_____________|
|1 | John |
|2 | Steve |
|3 | Williams |
|4 | Thomas |
|5 | James |
|______|_____________|
Table 3- Lastname
____________________
|eid | lname |
|______|____________|
|1 | Williams |
|2 | George |
|3 | Smith |
|4 | Robert |
|5 | Heart |
|___________________|
user can search with keyword 'will' or 'williams'. i need to search this key word from all the above 3 tables and display uid, fname and lname for that respective keyword. example: 1.John Williams 3.Williams Smith 5.James Heart
i tried union along with like '%will%'but there are duplicates returned in result. can someone help me with the query.
Thanks.
Assuming eid
is a foreign key to uid
, then something like this should work:
select u.uid, f.fname, l.lname
from users u
inner join firstname f on u.uid = f.eid
inner join lastname l on u.uid = l.eid
where f.fname like '%will%' or
l.lname like '%will%'
If you also need to search the uname field, then add that to your where criteria with another or statement.
Results:
UID FNAME LNAME
1 John Williams
3 Williams Smith
SELECT uid, uname, fname, lname
FROM Users
INNER JOIN firstname
ON firstname.eid = users.uid
INNER JOIN lastname
ON lastname.eid = users.uid
WHERE uname LIKE '%will%'
OR fname LIKE '%will%'
OR lname LIKE '%will%'
来源:https://stackoverflow.com/questions/16925584/search-from-multiple-tables-using-single-keyword-in-mysql