我已经编写了这个查询,以获得与用户一样多的行数+每个用户创建的潜在数量+已转换的所有潜力。这就是它的样子:
SELECT u.*, p.allPotentials, pc.cPotentials
FROM os_user u
JOIN (SELECT FID_author, count(*) allPotentials FROM os_potential) p
ON p.FID_author = u.ID
JOIN (SELECT converted, FID_author, count(*) cPotentials FROM os_potential) pc
ON p.FID_author = u.ID AND pc.converted = 1
我正在尝试使用不相关的子查询作为this answer explained me,我可以将我的查询组合成1.但是我得到0行。
我的表格如下:
用户:
+----+------+-------+
| ID | Name | Email |
+----+------+-------+
势:
+----+------+-------+------------+-----------+
| ID | Name | Email | FID_author | converted |
+----+------+-------+------------+-----------+
FID_author是外键,即用户ID。
我的查询返回0行并且没有显示错误。我做错了什么?
修改
到目前为止我的查询:
SELECT u.*, p.allPotentials, pc.cPotentials
FROM os_user u
LEFT JOIN (SELECT FID_author, count(*) allPotentials
FROM os_potential GROUP BY FID_author) p
ON p.FID_author = u.ID
LEFT JOIN (SELECT converted, FID_author, count(*) cPotentials
FROM os_potential GROUP BY FID_author) pc
ON p.FID_author = u.ID
AND pc.converted = 1
GROUP BY u.ID
我的结果几乎与预期一致,但问题是,cPotentials
每行包含1,这是错误的。有很多很多只有1.哪里可能是问题?
答案 0 :(得分:4)
在子查询中缺少组,并最终使用左连接
SELECT u.*, p.allPotentials, pc.cPotentials
FROM os_user u
LEFT JOIN (SELECT FID_author, count(*) allPotentials FROM os_potential
GROUP BY FID_author) p
ON p.FID_author = u.ID
LEFT JOIN (SELECT converted, FID_author, count(*) cPotentials FROM os_potential
GROUP BY converted,FID_author) pc
ON pc.FID_author = u.ID AND pc.converted = 1