我有这3张桌子
users [ id , username, password ]
logs [ id, user_id, action ]
user_propeties [ id, user_id, prop_name, prop_value ]
我想用Count(logs.id)和count(user_propeties.id)选择所有用户的列只有在2个表中prop_value IS为空时,具体取决于用户ID
我有以下查询
SELECT t1.*, count(t2.`id`) as total_logs,count(t3.`id`) as total_propeties
FROM `users` t1
LEFT JOIN `user_propeties` t2
ON t1.`id` = t2.`user_id` AND ISNULL(t2.`prop_value`)
LEFT JOIN `logs` t3
ON t3.`user_id` = t1.`id`
GROUP BY t1.id
ORDER BY t1.id DESC
返回行但计数值错误。我做错了什么?谢谢
答案 0 :(得分:1)
我怀疑你想要一些DISTINCT
,否则它将返回所有日志和属性组合的计数;
SELECT t1.*, COUNT(DISTINCT t2.`id`) as total_logs,
COUNT(DISTINCT t3.`id`) as total_propeties
FROM `users` t1
LEFT JOIN `user_propeties` t2
ON t1.`id` = t2.`user_id` AND ISNULL(t2.`prop_value`)
LEFT JOIN `logs` t3
ON t3.`user_id` = t1.`id`
GROUP BY t1.id
ORDER BY t1.id DESC