Jump to content

SELECT COUNT from mutiple tables


Psycho

Recommended Posts

I want to get the count of records from separate tables. Is it possible to do this with a single query?

Currently I am trying the following:

SELECT COUNT(g.genre_id) as genres, COUNT(m.movie_id) as movies\n"
FROM genres g, movies m

But instead of getting the values I expect where genres = the number of records in the genres table & movies = the number of records in the movies table; I am getting the same value for both which is the value of movies * genres.

So is it possible to pull records from separate tables w/o associating them or is there another way to run the query to get what I want. or should I just run separate queries (there are about 5 or 6 table in all - just included two for illustration purposes).
Link to comment
https://forums.phpfreaks.com/topic/27245-select-count-from-mutiple-tables/
Share on other sites

That's incredibly ineffecient... you're returning N^3 records for no reason, and then using DISTINCT which forces the use of a temporary table... check EXPLAIN and you'll see.

It's much better to use:

[code]
SELECT
( SELECT COUNT(movie_id) FROM movies ) as movies,
( SELECT COUNT(genre_id) FROM movies ) as genres,
( SELECT COUNT(studio_id) FROM movies ) as studios
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.