Mysql – Find the average number of n:m connections of two tables

MySQLstatistics

I want to know to how many lists a user is assigned in average.

User
====
id
name


Lists_Users
===========
user_id
list_id


List
====
id
title

Is there a good way of receiving this number via SQL?

Best Answer

You only need the counts from the 2 tables and a division:

SELECT 
    (SELECT COUNT(*) FROM Lists_Users)  /  (SELECT COUNT(*) FROM `User`) 
    AS average_lists_per_user ;  

If you want more statistical information, you can write it using derived tables:

SELECT 
    total_users, active_users, total_assignments, 
    total_assignments / total_users                  -- this is
        AS average_lists_per_user,                   -- what you want
    total_assignments / active_users 
        AS average_lists_per_active_user
FROM
    ( SELECT COUNT(*) AS total_assignments,
             COUNT(DISTINCT user_id) AS active_users
      FROM Lists_Users
    ) AS lu
  CROSS JOIN
    ( SELECT COUNT(*) AS total_users 
      FROM `User`
    ) AS u ;