我有一个名为 real_estate 的表,其结构和数据如下: -
| id | user_id | details | location | worth
| 1 | 1 | Null | Null | 10000000
| 2 | 1 | Null | Null | 20000000
| 3 | 2 | Null | Null | 10000000
我的查询是以下内容:
SELECT * , SUM( worth ) as sum
FROM real_estate
WHERE user_id = '1'
我从这个查询得到的结果是
| id | user_id | details | location | worth | sum
| 1 | 1 | Null | Null | 10000000 | 30000000
我希望结果像
| id | user_id | details | location | worth | sum
| 1 | 1 | Null | Null | 10000000 | 30000000
| 2 | 1 | Null | Null | 20000000 | 30000000
有没有办法以我想要的方式得到结果,还是应该写出2个不同的查询? 1)获得价值的总和 2)获取该用户的所有行
答案 0 :(得分:3)
您需要使用一个子查询来计算每个用户的总和,然后将子查询的结果与您的表一起加入:
SELECT real_estate.*, s.user_sum
FROM
real_estate INNER JOIN (SELECT user_id, SUM(worth) AS user_sum
FROM real_estate
GROUP BY user_id) s
ON real_estate.user_id = s.user_id
WHERE
user_id = '1'
但如果您只需要为单个用户返回记录,则可以使用:
SELECT
real_estate.*,
(SELECT SUM(worth) FROM real_estate WHERE user_id='1') AS user_sum
FROM
real_estate
WHERE
user_id='1'
答案 1 :(得分:1)
你可以在像这样的子查询中总结你的总和
SELECT * , (select SUM(worth) from real_estate WHERE user_id = '1' ) as sum
FROM real_estate WHERE user_id = '1'
答案 2 :(得分:0)
按 ID
分组SELECT * , SUM( worth ) as sum FROM real_estate WHERE user_id = '1' group by id