如果正确的字段存在,我如何使用左连接

时间:2016-05-17 14:17:59

标签: mysql if-statement join count where

我有两张桌子:

用户(查询中使用的字段) - >

 |uuid|name|last_name|email|rol        |status|
 |1234|abcd|   abc   |1@2.3|pre-thunder|  1   |
 |5678|efgh|   efg   |4@5.6|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)

此查询仅返回第一个用户,但无论是否有文档,我都需要返回所有用户。

有什么想法吗?我该怎么做?

1 个答案:

答案 0 :(得分:0)

由于您希望为每个用户返回count,因此您还应该使用group by。也许这就是你所追求的:

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