search from multiple tables using single keyword in mysql [duplicate]

醉酒当歌 提交于 2019-12-01 22:13:59

问题


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.


回答1:


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%'
  • SQL Fiddle Demo

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



回答2:


    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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!