'MySQL search multiple tables with different column names
I am trying to live search two tables in MySQL. I have the following query using UNION. When I get the result back, the keys are always from the first table columns only; [username], [pfp], [pro_bg_color]. How do I get the different table keys from the two different tables so I can sort through the data?
QUERY:
$query = "(SELECT `username`, `pfp`, `pro_bg_color`, 'user' AS `type` FROM `users` WHERE `username` LIKE '%{$ok['search_for']}%' AND account_status = 'active') ";
$query .= " UNION ";
$query .= "(SELECT `cluster_id`, `pp_pfp`, `pp_name`, 'page' AS `type` FROM `pixelpage` WHERE `pp_name` LIKE '%{$ok['search_for']}%')";
OUTPUT:
Array
(
[0] => Array
(
[username] => demo
[pfp] => 43867771.jpg
[pro_bg_color] => 9ddd13
[type] => user
)
[1] => Array
(
[username] => jimmy
[pfp] => 43867770.jpg
[pro_bg_color] => 2a00ff
[type] => user
)
[2] => Array
(
[username] => 1004
[pfp] => 2201fc2d.jpg
[pro_bg_color] => My Page Title
[type] => page
)
)
Solution 1:[1]
I worked it out as follows:
$query = "(SELECT `user_id` AS `id`, `username` AS `name`, `pfp` AS `pic`, `pro_bg_color` AS `bg_color`, 'user' AS `type` FROM `users` WHERE `username` LIKE '%{$ok['search_for']}%' AND account_status = 'active') ";
$query .= " UNION ";
$query .= "(SELECT `cluster_id` AS `id`, `pp_name` AS `name`, `pp_pfp` AS `pic`, `pp_banner` AS `bg_color`, 'page' AS `type` FROM `pixelpage` WHERE `pp_name` LIKE '%{$ok['search_for']}%')";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
