我有一个从查询返回的已观看视频 (1017) 的用户列表:
select distinct user_id from video_views
where video_viewable_id = 1017;
根据以下查询,我还有一组不同的用户(付费):
select id, is_paying_customer from users
where is_paying_customer = '1';
video_views表中的user_id与users表中的id相同。如何编写一个查询来显示观看视频且付费客户的用户列表?
最佳答案
select distinct user_id from video_views
where video_viewable_id = 1017 and user_id in (select id from users
where is_paying_customer = '1')
或者您可以使用连接语法
select distinct user_id from video_views
inner join users as t on (video_views.user_id=t.id and t.is_paying_customer = '1')
where video_viewable_id = 1017
另外,由于用户是主表,我会这样做:
select id from users where is_paying_customer = '1' and
`id` in (select user_id from from video_views where video_viewable_id = 1017)
在这种情况下,你不需要distinct,mysql将有效地使用索引
关于mysql - 如何合并sql查询之间的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325302/