Hi i know basic MySQL query format, but now i have a need to do some complex query.
say (for explanation purpose)
i have 3 tables with column id, item_name, and no_of_views.
i want to a single query to get top 10 viewed items from these 3 table.
Table1
id: item_name no_of_views
1 item1 20
2 item2 25
3 item3 16
4 item4 10
Table2
id: item_name no_of_views
1 itemA 2
2 itemB 5
3 itemC 70
4 itemD 0
Table3
id: item_name no_of_views
1 item_1 34
2 item_2 55
3 item_3 10
4 item_4 1
i know i have to join these tables and then query based on no_of views
like
$query="
(SELECT * FROM Table2)
UNION ALL
(SELECT * FROM Table2)
UNION ALL
(SELECT * FROM Table2)
ORDER by no_of _views DESC LIMIT 10";
This works perfectly fine but my problem is my tables have 100’s of item in them and i have many tables, if this is the way i do it the query will have to get all the results from all the tables and then give me only top 10 views,
i want to do it like selecting only 10 values from all tables based on no of views
like say i have 10 tables and each one have a no_of_views, how can i query to see which item has higest views among all tables and then next lower no_of_views from another table or same table which ever is true and so on.
is that even possible.
please suggest.
When comparing your query to the following query, the MySQL Execution plans are identical. The optimizer will still only be selecting the top 10 from each table (not the full record set) and then comparing them as that is the maximum it will need. This method is not as inefficient as you seem to believe.