我正在尝试对以下内容运行查询:
用户表有id和is_paying。 订阅表具有id,user_id和subscription_plan
我想获得具有subscription_plan = 81和is_paying ='Y'的用户的用户ID列表。我跑的时候
select count(distinct users.email)
from users,subscriptions
where subscription_plan_id=81
and users.is_paying_customer = 'Y';
查询运行的时间太长,因为我不认为它将两个表连接在一起,我不确定如何执行此操作。有什么建议吗?
答案 0 :(得分:1)
要获取用户列表,请删除COUNT
。此外,您需要设置JOIN条件以将用户与订阅相结合:
select DISTINCT users.email
from users JOIN subscriptions ON users.id = subscriptions.user_id
where subscription_plan_id=81
and users.is_paying_customer = 'Y';
答案 1 :(得分:0)
要正确加入表格,您需要在它们之间找到一些共同点。基本语法是
SELECT fields from Table1 aliasname
JOIN Table2 aliasname ON
table1aliasname.commonfield = table2aliasname.commonfield
WHERE wherecriteria
在这种情况下:
select count(distinct users.email)
from users,subscriptions
where subscription_plan_id=81
and users.is_paying_customer = 'Y';
将用户与描述联系起来的内容..我假设您有一个名为userID的字段 尝试这样的事情:
select count(distinct users.email)
from users u
JOIN subscriptions s on u.userid = s.userid
where subscription_plan_id=81
and users.is_paying_customer = 'Y';
答案 2 :(得分:0)
SELECT COUNT(*)
FROM (
SELECT DISTINCT users.id
FROM users INNER JOIN Subscriptions ON users.id = Subscriptions.user_id
WHERE (Subscriptions.subscription_plan_id = 81) AND (users.is_paying_customer = 'Y')
) AS DistinctUsers