2016-01-18 28 views
0

我有一個表格拖尾,用戶可以記錄他們在項目上花費的時間。聲明有開始和結束時間。即使在WHERE語句不匹配的情況下,也可以顯示錶中的所有行

我想要一個特定的項目(id = 1),即每個用戶花費在項目上的秒數,,即使用戶沒有花費任何時間在項目上

表(簡體):

users 
----- 
- id 
- name 
- ... 

projects 
-------- 
- id 
- name 

declarations 
------------ 
- id 
- user_id 
- project_id 
- begin 
- end 

假設有2個用戶。用戶ID = 1在項目上花費了一些時間,用戶ID = 2沒有做任何事情。

select users.*, sum(timestampdiff(second, declarations.start, declarations.end)) as seconds 
from  users 
join  declarations on declarations.user_id = users.id 
where declarations.project_id = 1 
group by users.id 

通過上述查詢,只有用戶1會出現。如何修改查詢以包含所有其他用戶以及的seconds值?

+0

嗯,怎麼樣去除where條件? –

+0

@TuanAnhTran然後所有的項目都會出現,我只想要一個特定的項目。如果用戶2沒有參與任何項目,問題仍然存在。 – Thijs

+0

我的不好。沒有仔細閱讀這個問題 –

回答

0

考慮使用LEFT OUTER JOIN並移動WHERE條件JOIN ON條件像

select users.*, 
sum(timestampdiff(second, declarations.start, declarations.end)) as seconds 
from users 
left join declarations on declarations.user_id = users.id 
and declarations.project_id = 1 
group by users.id 
+0

感謝您的回覆。不幸的是,這個解決方案與評論部分 – Thijs

+0

@Thijs中@TuanAnhTran的建議有相同的問題,不應該如此。請注意,我已經使用了左連接而不是內連接來獲取所有用戶。 – Rahul

+0

啊,太棒了,我讀了額外的project_id = 1限制加入。謝謝,工作:)事實上這麼簡單,但我根本沒有看到它 – Thijs

相關問題