【发布时间】:2013-03-03 16:28:44
【问题描述】:
我有 2 个表格来收集积分事件记录。
CREATE TABLE report_one
(
date timestamp,
point_id bigint,
income int
)
CREATE TABLE report_two
(
date timestamp,
point_id bigint,
spent int
)
我想生成一个总和报告(和其他报告)。我想使用join,因为我需要支持分页、排序...
问题是连接键(报告的点 id)不是 1:1 ,所以我得到的同一行不止一个。
insert into report_one values('2013-1-1',1,1)
insert into report_two values('2013-1-1',1,1)
insert into report_two values('2013-1-2',1,1)
select * from report_one r1 left join report_two r2 on r1.point_id = r2.point_id
将有 2 行表 report_one ,但总共我只需要一个。 我希望能够创建表之间某种连接的视图,其中每行只有一次。
**我想要这样的输出:
1 (pid) , 1,1,0,0 - 这个来自 report_one
1 (pid) ,0,0,1,1——来自report_two
1 (pid) ,0,0,1,1 -- 这来自 report_two **
Union all 可以很好,但我在两个表中没有相同的列类型。
附言。真正的表格有很多列,而 pk 不止一列,我只是为了这个问题而简单
【问题讨论】:
-
您要查找的预期输出数据是什么?
-
我添加了预期的输出
-
您为什么不能有一个report_id 而不是为每个报告创建表格?那你就不用加入了,可以按report_id分组吗?