2016-05-17 72 views
0

我有兩個表:LEFT JOIN如何使用其中,如果右場存在

用戶(使用的字段查詢) - >

|uuid|name|last_name|email|rol  |status| 
|1234|abcd| abc |[email protected]|pre-thunder| 1 | 
|5678|efgh| efg |[email protected]|pre-thunder| 1 | 

而且documentation_thunder表(在查詢中使用的字段) - >

|id|id_thunder|doc_type| 
|1 |1234  |image | 

我儘量讓我的左表中的所有記錄,但更多的,我從我的右表中獲取計數:

SELECT 
users.uuid, 
users.email, 
users.name, 
users.last_name, 
COUNT(documentation_thunder.id) as documentation// i need to know how many documents have the user 
FROM users 
LEFT JOIN documentation_thunder 
    ON users.uuid = documentation_thunder.id_thunder 
WHERE 
users.status = 1 AND users.rol = 'pre-thunder' AND (documentation_thunder.doc_type = 'image' OR documentation_thunder.doc_type IS NULL) 

此查詢只返回第一個用戶,但我需要返回所有用戶,不管是否有文檔。

有什麼想法?我該怎麼做?

回答

0

既然你想爲每個用戶返回一個count,你應該也使用group by。也許這是你以後在做什麼:Whoooaaaa你是最好的

SELECT 
users.uuid, 
users.email, 
users.name, 
users.last_name, 
COUNT(documentation_thunder.id) as documentation 
FROM users 
LEFT JOIN documentation_thunder 
    ON users.uuid = documentation_thunder.id_thunder 
WHERE 
users.status = 1 AND users.rol = 'pre-thunder' AND 
(documentation_thunder.doc_type = 'image' OR documentation_thunder.doc_type IS NULL) 
GROUP BY users.uuid 
+0

。謝謝Giorgos –