开发者

MySQL Multi Table Search

table1
 ID
 SUBJECT
 CONTENT

table2
 ID
 SUBJECT
 CONTENT

table3
 ID
 SUBJECT
 CONTENT

... 5 more

I want to search SUBJECT on all the tables

Ho开发者_C百科w can I do this?


CREATE VIEW multitable AS
SELECT * FROM table1
UNION SELECT * from table2
UNION SELECT * from table3;

SELECT subject FROM multitable ...


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%'


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜