Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search multiple tables for the same value

Tags:

database

mysql

I have a MYSQL database with a few tables, all of which have the same structure. I want to search all the tables to find a row with a specific value for a column. Do I have to search the tables one by one or there is an easier way?

like image 625
Psirogiannis Dimitris Avatar asked Feb 05 '15 19:02

Psirogiannis Dimitris


2 Answers

You can union all tables. You still need traverse all tables one by one, but in case of union you will not have cartesian multiplication, hence best from all:

SELECT column FROM table1 WHERE column = 'value'
UNION ALL
SELECT column FROM table2 WHERE column = 'value'
;
like image 165
cn007b Avatar answered Nov 14 '22 09:11

cn007b


Easily done and ALSO TESTED IN MYSQL WORKBENCH.

SELECT ALL:

SELECT * FROM table_one, table_two;

SELECT ONE VALUE FROM TWO TABLES:

SELECT * FROM table_one, table_two WHERE field = 'some_val'

SELECT MULTIPLE VALUES FROM TWO TABLES:

SELECT * FROM table_one, table_two WHERE field = 'some_val' AND field2 = 'some_val' AND field3 = 'some_val'
like image 32
technology101010 Avatar answered Nov 14 '22 10:11

technology101010