我有2张桌子
请求
requests_votes
请求结构是:
id | req_name | content | hits
------------------------------
1 | Sample | Some | NULL
2 | Sample | Some | NULL
3 | Sample | Some | NULL
4 | Sample | Some | NULL
5 | Sample | Some | NULL
requests_votes结构是:
id | requestid | user_id
------------------------
10 | 2 | 2556
18 | 2 | 2522
33 | 3 | 120
44 | 2 | 1559
98 | 5 | 253
宽度以下查询我能够计算投票如何具有项目(请求)
SELECT `requestid` , count( requests_votes.id ) AS totals
FROM `requests_votes`
INNER JOIN `requests` ON requests.id = requests_votes.requestid
GROUP BY `requestid`
输出:
requestid | totals
------------------
2 | 3
3 | 1
5 | 1
我想在 count(requests_votes.id)结果中填充请求表中的 hits 列。
我已经讨论了stackoverflow中提到的类似问题,但找不到解决方案。
答案 0 :(得分:1)
您可以在JOIN
查询中使用UPDATE
:
UPDATE `requests` T1 JOIN
(SELECT `requestid` , count( requests_votes.id ) AS totals
FROM `requests_votes`
INNER JOIN `requests` ON requests.id = requests_votes.requestid
GROUP BY `requestid`) T2 ON T1.id=T2.requestid
SET T1.hits=T2.totals