我有两张桌子:
**user**
idU - autoincrement
name
**automobile**
idA - autoincrement
id_user
value
date - type: yyyy-mm-dd
每个用户都有很多汽车 汽车只有一个用户
目前我对所有用户使用以下查询(总共5个):
select sum(value) as user_value, name
from user inner join automobile on user.idU = automobile.id_user
where name like ? AND date = ?
我想要什么?我希望使用1个查询在特定日期中所有用户的总价值。我怎么能这样做?
@ EDIT1:
TABLE USER
--idU------name----
1 mateus
2 joao
3 maria
TABLE AUTOMOBILE
--idA---id_user----value-------date------
1 1 250 2013-10-13
2 3 322 2013-10-13
3 1 150 2013-10-13
4 3 80 2013-10-13
5 2 100 2013-11-13
6 3 500 2013-11-13
7 1 1100 2013-11-13
8 1 50 2013-12-13
9 3 135 2013-12-13
10 2 40 2013-12-13
我请求日期= 2013-10-13的查询并返回:
---name---value
mateus 400
maria 422
答案 0 :(得分:2)
类似的东西:
select sum(value) as user_value,
name inner join automobile on user.idU = automobile.id_user
where date = ?
group by user.idU
----------- ------------ EDIT
select name, sum(value) as value
from user inner join automobile on user.idU = automobile.id_user
where date = "2013-10-13"
group by automobile.id_user
SQLFiddle:http://sqlfiddle.com/#!2/8115c/4
答案 1 :(得分:1)
我不确定我是否做对了。由于您使用的是聚合函数('sum'),因此通常只返回包含值总和的一行。但是如果你想要执行查询,也许这会有所帮助(未经测试)..
SELECT
SUM(automobile.value) as totalValue,
user.name
FROM
automobile
INNER JOIN
user
ON automobile.id_user = user.idu
WHERE
automobile.date between '2013-10-13' and '2013-10-13'
GROUP BY
automobile.id_user
答案 2 :(得分:1)
假设您想要一个具有特定日期的汽车总价值的每个用户的列表,您需要按照您选择的任何用户字段进行分组:
SELECT
SUM(a.value) as user_value,
u.name
FROM
user u INNER JOIN
automobile a on u.idU = a.id_user
WHERE
a.date = ?
GROUP BY
u.name