sql选择大多数用户的产品

时间:2013-02-11 12:26:28

标签: mysql sql

用户:

uid int(11) - userid(primary key, auto_increment)
name varchar(255)
pass varchar(64)
created int(11)

项目:

pid int(11) .....
name varchar(150)
description varchar(255)
created int(11)

users_projects:

uid int(11) - user id
pid int(11) - product id

如何选择分配给最多用户的项目?

sql查询。

3 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

select p.pid, 
  p.name,
  up.TotalUsers
from projects p
inner join
(
  select pid, count(uid) TotalUsers
  from users_projects
  group by pid
) up
  on p.pid = up.pid
order by TotalUsers Desc
-- limit 1

请参阅SQL Fiddle with Demo

这将返回所有项目的列表以及每个项目的总用户数。如果您想让大多数用户返回项目,那么您将包含已注释掉的limit 1

如果您有多个project具有相同数量的用户,那么您可能希望使用与此类似的内容:

select p.pid, 
  p.name,
  up.TotalUsers
from projects p
inner join
(
  select pid, count(uid) TotalUsers
  from users_projects
  group by pid
) up
  on p.pid = up.pid
where totalusers = (select count(*) Total
                    from users_projects
                    group by pid
                    order by total desc
                    limit 1)

请参阅SQL Fiddle with Demo

感谢小提琴的@JW

答案 1 :(得分:1)

以下查询将包含具有相同用户数的多个项目,并且恰好是最多的用户。

SELECT  a.name userName, c.name ProjectName
FROM    users a
        INNER JOIN users_projects b
            ON a.uid = b.uid
        INNER JOIN projects c
            ON b.pid = c.pid
        INNER JOIN
        (
            SELECT  pid, COUNT(*) totalCount
            FROM    users_projects
            GROUP   BY pid
            HAVING  COUNT(*) = (SELECT COUNT(*) x 
                                FROM users_projects 
                                GROUP BY pid 
                                ORDER BY x DESC 
                                LIMIT 1)
        ) d ON b.pid = d.pid
ORDER   BY a.Name ASC

答案 2 :(得分:0)

如果您只查找一个项目,以下是最快的方法:

select project_id, count(*) as NumUsers
from user_projects
group by project_id
order by count(*) desc
limit 1

(我假设“产品”=“项目”)。