patternsqlMinor
Count multiple tables as one count
Viewed 0 times
onecounttablesmultiple
Problem
I have seen how to do multiple counts for different tables, but never how to combine them all into one. I have a MySQL DB where I am running the following query:
This is giving me the following which is great:
I want to get a combined count of all of the 'wiki_xxxx' tables. For example I want 'wiki_items'(above) + 'wiki_armors' + 'wiki_weapons' + ...
Thanks for any help :D
SELECT characters.name, COUNT(*) AS wiki_unlocks
FROM wiki_items
INNER JOIN characters
ON characters.character_id=wiki_items.character_id
GROUP BY wiki_items.character_id
ORDER BY wiki_unlocks DESC
LIMIT 10;This is giving me the following which is great:
name wiki_unlocks
player1 2
player2 1I want to get a combined count of all of the 'wiki_xxxx' tables. For example I want 'wiki_items'(above) + 'wiki_armors' + 'wiki_weapons' + ...
Thanks for any help :D
Solution
It's probably easiest to do each count as a subselect:
SELECT c.name
, (select COUNT(i.character_id)
From wiki_items i
Where c.character_id=i.character_id
) as wiki_unlocks
, (select COUNT(a.character_id)
From wiki_armors a
Where c.character_id=a.character_id
) as wiki_armors
, (select COUNT(w.character_id)
From wiki_weapons w
Where c.character_id=w.character_id
) as wiki_weapons
FROM characters cCode Snippets
SELECT c.name
, (select COUNT(i.character_id)
From wiki_items i
Where c.character_id=i.character_id
) as wiki_unlocks
, (select COUNT(a.character_id)
From wiki_armors a
Where c.character_id=a.character_id
) as wiki_armors
, (select COUNT(w.character_id)
From wiki_weapons w
Where c.character_id=w.character_id
) as wiki_weapons
FROM characters cContext
StackExchange Database Administrators Q#87412, answer score: 2
Revisions (0)
No revisions yet.