Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search SQL query from multiple tables MySQL

Tags:

search

mysql

I am trying to perform search on multiple tables.

I will simplify problem and say that I have 2 tables Worker and Customer both have Id, Name, Surname and Worker has additional Position, all fields are varchar except Id which is Int.

How to make a query that will return rows of either Customer or Worker, where one of theirs fields contains entered search string.

I have tried with joins but I got returned joined row also.

like image 906
eomeroff Avatar asked May 01 '11 23:05

eomeroff


2 Answers

select id,name,surname,position,'worker' as tbl from worker where ..
union all
select id,name,surname,'','customer' from customer where ...

In this way you can even know results what table belong to.

like image 54
Nicola Cossu Avatar answered Sep 21 '22 13:09

Nicola Cossu


Just UNION both queries.
If you really can JOIN those two, you can use an IF statement in the SELECT clause to show the right field.
But, from what I understand from your question, go with UNION

like image 35
Itay Moav -Malimovka Avatar answered Sep 19 '22 13:09

Itay Moav -Malimovka