2015-11-13 101 views
0

我想为项目列表创建一个查询,该列表将提供已注册应用程序的数量,但不包括用户不存在的数量。 在这种情况下,考虑用户10不存在,我应该有查询结果folows:从另一个表中的一个用户表中计算行

成绩

+----+------------+--------------+ 
    | id | project | applications | 
    +----+------------+--------------+ 
    | 1 | MyProject1 |   3 | 
    | 2 | MyProject2 |   0 | 
    | 3 | MyProject3 |   0 | 
    +----+------------+--------------+ 

TABLES

Projects 
+----+------------+ 
| id | name | 
+----+------------+ 
| 1 | MyProject1 | 
| 2 | MyProject2 | 
| 3 | MyProject3 | 
+----+------------+ 


applications 
+----+------+------------+ 
| id | user | project_id | 
+----+------+------------+ 
| 1 | 3 |   1 | 
| 2 | 4 |   1 | 
| 3 | 5 |   1 | 
| 4 | 10 |   1 | 
+----+------+------------+ 



users 
+----+---------+ 
| id | Name | 
+----+---------+ 
| 1 | Smith | 
| 2 | John | 
| 3 | Paul | 
| 4 | Chris | 
| 5 | Gabriel | 
+----+---------+ 

下面的查询不排除非现有用户:

SELECT `projects` . * , (

                       SELECT COUNT(*) 
                       FROM `applications` 
                       WHERE `applications`.`project_id` = `projects`.`id` 
                       AND EXISTS (
                       SELECT `applications`.`id` 
                       FROM `applications` , `users`,`project` 
                       WHERE `application`.`user` = `users`.`id` AND `applications`.`project_id` = `project`.`id` 
                       ) 
                       ) AS `applications` 
                       FROM `projects` ORDER BY `id` DESC LIMIT 30 
+1

这看起来很可怕。表格应用程序中如何存在表格用户中不存在的用户ID?应该有一个外键。或者有没有理由不这样做? –

回答

0

您的查询似乎过于复杂。这应该这样做:

select 
    id, 
    name as project, 
    (
    select count(*) 
    from applications a 
    where a.project_id = p.id 
    and a.user in (select id from users) 
) as applications 
from projects p; 
1

我想你想要left joingroup by

select p.id, p.name, count(u.id) 
from projects p left join 
    applications a 
    on p.id = a.project_id left join 
    users u 
    on a.user_id = u.id 
group by p.id, p.name; 

但是,您可能要考虑固定的数据。看起来应用程序和项目以及应用程序和用户之间应该有外键关系。拥有无效用户的能力意味着与用户没有有效的外键关系。

+0

这个运行速度很慢。 我已经在帖子编辑中尝试了查询,但它不排除不存在的用户: – valiD

+0

在> u.id不为空的情况下为左连接添加测试 –

+0

@valiD。 。 。 (1)如果你在表上有主键,这应该相当快; (2)这不应该被视为不存在的用户。这就是'count(u.id)'所做的。 –

0

根据以往的解决方案

select p.id, p.name, count(u.id) 
from projects p left join 
    applications a 
    on p.id = a.project_id left join 
    users u 
    on a.user = u.id 
where u.id is not null 
group by p.id, p.name; 

当你做一个左连接,如果搜索值不存在,则返回null。然后通过排除空用户进行筛选,会给出结果。

请找sqlfiddle来说明吧:http://www.sqlfiddle.com/#!9/cbfec6/3

但最简单的解决办法是

select p.id, p.name, count(u.id) 
from projects p,applications a, users u 
where a.user = u.id 
and p.id = a.project_id 
group by p.id, p.name; 
相关问题