很简单的问题.我想要做的是从一个表中选择所有列,并从另一个表中选择一列(可能有多个匹配的行)的总和. 例: table ta (eid, uid, name, year, etc, etc, etc)table tb (eid, uid, name, year, amount, etc, e
例:
table ta (eid, uid, name, year, etc, etc, etc) table tb (eid, uid, name, year, amount, etc, etc)
eid – 两个表之间不匹配
uid,name,year – 将在两个表中匹配
所以我想从表ta中提取所有列,简单:
select * from ta where eid='value';
我想将表tb中的amount列加到我的结果集中,简单:
select a.*, b.amount from ta a inner join tb b on a.year=b.year where a.eid='value';
太好了,这很好用.但是如果我在表tb中有多行呢?
执行:
select a.*, sum(b.amount) from ta a inner join tb b on a.uid=b.uid where a.year='value';
给我以下错误:
Column ‘ta.eid’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
所以我补充说:
select a.*, sum(b.amount) from ta a inner join tb b on a.uid=b.uid where a.year='value' group by ta.uid;
我得到同样的错误!
但是,如果我将查询更改为:
select a.uid, a.year, sum(b.amount) from ta a inner join tb b on a.uid=b.uid where a.year='value' group by ta.uid, ta.year;
它有效,但现在我有三列而不是我想要的所有列.
所以,在这一点上,我的问题变成:除了我手动输入我想从两个带有GROUP BY子句的表中拉出的所有列之外,是否有更好,更清晰的结构化查询方式?
您可以在子查询中预聚合:select a.*, b.sumb from ta a left join (select b.uid, sum(b.amount) as sumb from tb b group by b.uid ) b on a.uid=b.uid where a.year = 'value';