我有3个表格如下:
acc_prop
id | pid | uid
1 | 10 | 1
2 | 11 | 1
3 | 12 | 1
卡
id | pid
1 | 10
2 | 11
3 | 12
价
cid | rate
1 | 100
2 | 99
3 | 130
我想创建一个返回pid的查询,一个具有相同uid的uid的计数,以及该pid的速率。
预期结果
pid | uid_count | rate
10 | 3 | 100
11 | 3 | 99
12 | 3 | 130
我的查询看起来像这样
SELECT
cal.pid,
count(ap3.uid) as uid_count,
price.rate
FROM
price
JOIN
cal on cal.id = price.cid
JOIN
acc_prop ap using(pid)
JOIN
acc_prop ap2 on ap2.uid = ap.uid
JOIN
acc_prop ap3 on ap3.uid = ap2.uid
group by ap3.pid;
但它返回
实际结果
pid | uid_count | rate
10 | 9 | 100
10 | 9 | 100
答案 0 :(得分:0)
我认为这里不需要cal,你试过这个吗?
SELECT
acc_prop.pid, (SELECT COUNT(*) FROM acc_prop WHERE uid = uid) AS uid_count, price.rate
FROM
acc_prop
INNER JOIN price
ON acc_prop.id = price.cid
答案 1 :(得分:0)
我认为你所追求的是这个,即预先计算acc_prop
中作为派生表的用户数量,然后你可以将其加入到查询的其余部分:
SELECT
cal.pid,
UserCount.Cnt,
price.rate
FROM
price
JOIN cal on cal.id = price.cid
JOIN acc_prop ap using(pid)
JOIN
(
SELECT uid, COUNT(*) AS Cnt
FROM acc_prop
GROUP BY uid
) UserCount
ON ap.uid = UserCount.uid;