Reputation: 109
SELECT DISTINCT ID FROM (SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4 ORDER BY total_hits DESC) AS sumtbl LIMIT 50;
This query works fine and selects unique ID's ordered by total_hits DESC
, the question is how can I return total_hits
column too having Id's unique?
Upvotes: 1
Views: 472
Reputation: 4636
If you want the total_hits FROM all the ids across all the tables, you'll need to do a sum / group by. Not sure if this is what you're asking since the question is vague...
SELECT DISTINCT id, sum(total_hits) total_hits
FROM (SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4) AS sumtbl
GROUP BY id
ORDER BY total_hits DESC
LIMIT 50
Also, don't use select * as it's bad practice, esp. if you go to add a column to one of those tables and not the others, your whole query will break.
Upvotes: 0
Reputation: 37354
UPDATE
In your case you can do
SELECT ID, MAX(total_hits) as max_hits
FROM (
SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4
)sumtbl
GROUP BY ID
ORDER BY max_hits DESC
LIMIT 50
Note : you don't need ORDER BY
in derived query, it goes to upper
Also, it would be better, if you
SELECT id, total_hits
etc. rather then selecting all fields from tables in your derived query.
FROM tbl1
UNION ALL
SELECT id, total_hits FROM tbl2
Upvotes: -1
Reputation: 171391
SELECT ID, SUM(total_hits)
FROM (
SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4
) AS sumtbl
GROUP BY ID
ORDER BY SUM(total_hits) DESC
LIMIT 50;
Upvotes: 2