Redshift 查询以计算除他们创建的用户之外的用户观看的票数
Redshift query to count number of tickets watching by the users except the ones they created
我们的票务系统中有 2 张桌子。在这个系统中,用户可以创建门票,任意数量的用户可以观看一张或多张门票。
为此,我们设置了 2 个表:
- 存储手表信息 -
watch_table
- 存储所有权信息 -
ownership_table
watch_table
ticket_id | watched_by
=======================
t1 | u1
t2 | u2
t2 | u1
ownership_table
ticket_id | owned_by
=====================
t1 | u1
t2 | u2
我想提取每个用户的观看次数。但是,不包括自己门票上的手表。
例如,在上面的例子中,输出应该是:
output:
user_id | count
================
u1 | 1
u2 | 0
我可以使用子查询创建查询来执行此操作。如下所示:
select watched_by as user_id, count(*) from watch_table wt where
(select count(*) from ownership_table where owned_by = wt.watched_by and ticket_id = wt.ticket_id) = 0
group by watched_by
我的问题是如何使用联接执行此操作,哪个性能更高?
根据您的示例数据,您可能可以使用 outer join
select t.owned_by as User_Id, Count(w.ticket_id) as count
from ownership_table t
left join watch_table w on w.watched_by=t.owned_by and w.ticket_Id != t.ticket_Id
group by t.owned_by
替代方法可能是相关子查询:
select Owned_By as User_Id, (
select Count(*)
from watch_table w
where w.watched_by=t.Owned_by and w.ticket_Id != t.ticket_Id
)
from ownership_table t
select w.userid, count(o.ticketid)
from watches w left join owners o
on o.ticketid = w.ticketid and o.userid <> w.userid
group by w.userid
https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=19901f70822260cc943e6e51b42c7fbe
我们的票务系统中有 2 张桌子。在这个系统中,用户可以创建门票,任意数量的用户可以观看一张或多张门票。
为此,我们设置了 2 个表:
- 存储手表信息 -
watch_table
- 存储所有权信息 -
ownership_table
watch_table
ticket_id | watched_by
=======================
t1 | u1
t2 | u2
t2 | u1
ownership_table
ticket_id | owned_by
=====================
t1 | u1
t2 | u2
我想提取每个用户的观看次数。但是,不包括自己门票上的手表。
例如,在上面的例子中,输出应该是:
output:
user_id | count
================
u1 | 1
u2 | 0
我可以使用子查询创建查询来执行此操作。如下所示:
select watched_by as user_id, count(*) from watch_table wt where
(select count(*) from ownership_table where owned_by = wt.watched_by and ticket_id = wt.ticket_id) = 0
group by watched_by
我的问题是如何使用联接执行此操作,哪个性能更高?
根据您的示例数据,您可能可以使用 outer join
select t.owned_by as User_Id, Count(w.ticket_id) as count
from ownership_table t
left join watch_table w on w.watched_by=t.owned_by and w.ticket_Id != t.ticket_Id
group by t.owned_by
替代方法可能是相关子查询:
select Owned_By as User_Id, (
select Count(*)
from watch_table w
where w.watched_by=t.Owned_by and w.ticket_Id != t.ticket_Id
)
from ownership_table t
select w.userid, count(o.ticketid)
from watches w left join owners o
on o.ticketid = w.ticketid and o.userid <> w.userid
group by w.userid
https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=19901f70822260cc943e6e51b42c7fbe