mysql - 如何合并sql查询之间的列表?

标签 mysql sql

我有一个从查询返回的已观看视频 (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/

相关文章:

mysql - MySQL 中的自然连接与匹配列

SQL Server 2008 R2 和端口 61303

mysql - 使用多个条件和子查询进行选择

php - 使用 PHP 从 MySQL 检索图像

mysql - SQL合并不同行的结果,按case合并

结果可以在不同列中的最后 x 个结果的 MySQL sum avg

mysql - 在 mysql 中,如何只从一个表中获取不链接到具有特定 ID 的另一个表中的任何行的行

java - 如何消除这个jsp错误

php - 在 PHP 中组合 sql 查询

php - 将我的失败 æøå 字符替换为 MySQL 或 PHP cde 中的 æøå