search from multiple tables using single keyword i

2019-07-03 10:54发布

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.

标签: mysql keyword
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-03 11:39

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
查看更多
Evening l夕情丶
3楼-- · 2019-07-03 11:45
    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%'
查看更多
登录 后发表回答