跨中介表交叉加入

时间:2017-08-16 14:44:43

标签: postgresql cross-join

我有一个包含3个表的数据库:群组时间段,用户和事件。

群组有很多用户,每个用户都有很多事件。同组群也有与其相关的时间段。我想知道每个队列,每个时期发生了多少事件。

如果有2个表格会很容易做CROSS JOIN但是当有这个中间表时我就被卡住了。

这是数据库结构:

create table time_periods (
  cohort_name varchar,
  period_name varchar,
  start_time timestamp,
  end_time timestamp);

create table users (
  cohort_name varchar,
  user_name varchar
);

create table events (
  user_name varchar,
  ts timestamp);

insert into time_periods values
('cohort1', 'first', '2017-01-01', '2017-01-10'),
('cohort1', 'second', '2017-01-10', '2017-01-20'),
('cohort2', 'first', '2017-01-15', '2017-01-20');

insert into users values
  ('cohort1', 'alice'),
  ('cohort2', 'bob');

insert into events values 
('alice', '2017-01-07'),
('alice', '2017-01-17'),
('bob', '2017-01-18');

这就是我可以使用SQL - 进行三重交叉连接但是它不正确 - 结果是6个事件,当它应该只是每行1个。

select
  time_periods.cohort_name,
  period_name,
  count(ts)
from time_periods, users, events
group by 1, 2
order by time_periods.cohort_name

这是SQLFiddle:

http://sqlfiddle.com/#!17/b141e/2

1 个答案:

答案 0 :(得分:1)

您需要指定要加入表的列 如果我正确理解您的数据,您需要这样的内容:

$('.someSelector')

在此处,您只能为正确同类群组中的用户加入select tp.cohort_name, tp.period_name, count(*) from time_periods tp inner join users u on tp.cohort_name = u.cohort_name inner join events e on u.user_name = e.user_name and e.ts between tp.start_time and tp.end_time group by 1, 2 order by tp.cohort_name time_periods,然后仅在特定时间段内为指定的用户和活动加入users,然后按1和2得到正确的偶数

相关问题