首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >跨中间表的交叉联接

跨中间表的交叉联接
EN

Stack Overflow用户
提问于 2017-08-16 22:44:43
回答 1查看 96关注 0票数 0

我有一个有3个表的数据库:队列时间段,用户和事件。

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

如果有两个表,那么做一个CROSS JOIN会很容易,但是当有这个中间表时,我就卡住了。

下面是DB结构:

代码语言:javascript
运行
复制
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个事件。

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-16 22:53:54

您需要指定要在哪些列上连接表,如果我正确理解了您的数据,您需要如下所示:

代码语言:javascript
运行
复制
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,然后仅针对特定时间段内的指定用户和事件加入到events,然后按1和2分组以获得正确的偶数计数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45716679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档