MySQL Multi Table Search

748 Views Asked by At
table1
 ID
 SUBJECT
 CONTENT

table2
 ID
 SUBJECT
 CONTENT

table3
 ID
 SUBJECT
 CONTENT

... 5 more

I want to search SUBJECT on all the tables

How can I do this?

3

There are 3 best solutions below

0
On
select * from table1 where subject like '%match%' union
select * from table2 where subject like '%match%' union
select * from table3 where subject like '%match%' union
select * from table4 where subject like '%match%' union
select * from table5 where subject like '%match%' union
select * from table6 where subject like '%match%' union
select * from table7 where subject like '%match%' union
select * from table8 where subject like '%match%'
2
On
CREATE VIEW multitable AS
SELECT * FROM table1
UNION SELECT * from table2
UNION SELECT * from table3;

SELECT subject FROM multitable ...
0
On

Because all the tables have the same syntax, you can use the UNION operator.

SELECT * FROM Table1
UNION Table2
UNION Table3
UNION Table4
UNION Table5
UNION Table6
UNION Table7
UNION Table8
WHERE SUBJECT="Subject"

For the sake of simplicity, 8 tables isn't too much to write out. If you had more, I'd recommend a dynamic query.