2015-11-13 135 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; 
相關問題