左连接如果存在右字段,我如何使用 where
Left join how can i use where if right field exists
我有两个 table:
用户(查询中使用的字段)->
|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 table(查询中使用的字段)->
|id|id_thunder|doc_type|
|1 |1234 |image |
我尝试获取左侧的所有记录 table 但另外我还从右侧获取计数 table:
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)
此查询仅 returns 第一个用户,但我需要 returns 所有用户,无论是否有文档。
有什么想法吗?我该怎么做?
既然你想为每个用户return一个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
我有两个 table:
用户(查询中使用的字段)->
|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 table(查询中使用的字段)->
|id|id_thunder|doc_type|
|1 |1234 |image |
我尝试获取左侧的所有记录 table 但另外我还从右侧获取计数 table:
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)
此查询仅 returns 第一个用户,但我需要 returns 所有用户,无论是否有文档。
有什么想法吗?我该怎么做?
既然你想为每个用户return一个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