我有两个表:
用户(查询中使用的字段)->
|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)
此查询仅返回第一个用户,但我需要返回所有用户,无论是否有文档。
有什么想法吗?我该怎么做?
最佳答案
由于您想要为每个用户返回计数
,因此您还应该使用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
关于mysql - 如果右字段存在,左连接如何使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278757/