简体   繁体   中英

MySQL getting count of a related table

My SQL's more than a little rusty, and I'm having trouble getting this to work, so any assistance would be greatly appreciated.

I've got three tables:

sessions
---------------
id

session_visits
---------------
id | session_id

searches
---------------
id | session_visit_id

And I want to get a list of all sessions with the total visits and searches for each sessions, which is linked by the session_visits table. I can get the visits fine, but am having trouble getting the total of searches for each session too.

So far I've got

SELECT *,(SELECT Count(*)    
          FROM session_visits    
          WHERE session_id = sessions.id) AS num_visits, 
         (SELECT Count(*)    
          FROM searches    
          WHERE session_visit_id = (SELECT * FROM session_visits    
                                    WHERE session_id = sessions.id)) AS total_searches
FROM sessions

Which is failing on every count! Am I going about this the right way or am I fundamentally doing it wrong?

You can do this in one query, by joining the 3 tables together, and then use aggregates COUNT DISTINCT (to eliminate duplicated) and COUNT to get the total number of rows for the child and grandchild rows respectively, grouped by the Sessionid.

SELECT s.id AS SessionId, COUNT(DISTINCT sv.id) AS SessionVisits, COUNT(sr.ID) AS Searches
FROM sessions s
  LEFT JOIN session_visits sv
  ON s.id = sv.session_id
  LEFT JOIN searches sr
  ON sr.session_visit_id = sv.id
GROUP BY s.id;

SqlFiddle here

( Edit : Changed to left outer joins to handle scenarios where there are no visits for session, or no searches per visit)

query generates error because of column name is not mentioned in query Operand should contain 1 column

and try with IN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM