Jump to content

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]

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.