How to search using the LIKE syntax and % WILDCARD % across multiple tables
Question
How can you use mysql and the like/wildcard syntax across multiple tables, would it be as simple as:
(SELECT * FROM `table1` WHERE `name` LIKE '%tom%') AND (SELECT * FROM `table2` WHERE `name` LIKE '%sam%')
Not tested, just thinking about it.
Solution
If your tables have the same structures, you can use UNION:
SELECT * FROM `table1` WHERE `name` LIKE '%tom%' UNION SELECT * FROM `table2` WHERE `name` LIKE '%sam%'
OTHER TIPS
Use UNION
(SELECT * FROM `table1` WHERE `name` LIKE '%tom%') UNION
(SELECT * FROM `table2` WHERE `name` LIKE '%sam%')
Actually if you use UNION, any duplicate rows may be removed. Use UNION ALL if you wish to retain any duplicates (say if you want to perform a COUNT on all rows matching %tom% in table1 and table2.
(SELECT * FROM `table1` WHERE `name` LIKE '%tom%') UNION ALL (SELECT * FROM `table2` WHERE `name` LIKE '%tom%')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow