我正在尝试编写查询。我已经完成一半了,但是在“左联接”方面遇到了问题。
我有三个表:
用户将始终只有一个user_preference,但在user_subscription_plan中可以有很多条目或没有条目
如果用户在user_subscription_plan中没有条目,或者只有一个条目,则我的sql有效。如果我有一个以上,那么我有问题。 在有两个条目的情况下,如何使它返回最后输入的一个?我尝试使用ORDER语句,但是它不能按预期工作。我不知何故得到了空行。
这是我的查询:
SELECT u.id AS GYM_USER_ID, subscription_plan.id AS subscriptionId, up.onboarding_completed AS CompletedOnboarding,
(CASE
WHEN ((up.onboarding_completed = 1)
AND (ISNULL(subscription_plan.id)))
THEN 'freemiun'
WHEN (ISNULL(up.onboarding_completed)
AND (ISNULL(subscription_plan.id)))
THEN 'not_paying'
END) AS subscription_status
FROM user AS u
INNER JOIN user_preferences up ON up.user_id = u.id
LEFT JOIN (
SELECT * FROM user_subscription_plan AS usp ORDER BY usp.id DESC LIMIT 1
) AS subscription_plan ON subscription_plan.user_id = u.id
GROUP BY u.id;
如果按原样运行,则 subscription_plan.id AS subscriptionId 始终为空。 如果我删除LIMIT子句,则它不是空的,但是我仍然得到第一个条目,对于我来说这是错误的
我要讲的案例更多,但是直到解决此问题我才能处理。
答案 0 :(得分:1)
请尝试使用“按subscription_plan.user_id分组”的“ max(usp.id)”,而不是限制1。
如果在子查询中限制1,则子查询的结果将始终仅返回1条记录(如果表中有数据)。 因此上面的查询可以这样重写。
对不起,我没有进行测试,因为我没有数据,但是请尝试,希望能对您有所帮助。
SELECT
u.id AS GYM_USER_ID,
subscription_plan.id AS subscriptionId,
up.onboarding_completed AS CompletedOnboarding,
(CASE
WHEN
((up.onboarding_completed = 1)
AND (ISNULL(subscription_plan.id)))
THEN
'freemiun'
WHEN
(ISNULL(up.onboarding_completed)
AND (ISNULL(subscription_plan.id)))
THEN
'not_paying'
END) AS subscription_status
FROM
user AS u
INNER JOIN
user_preferences up ON up.user_id = u.id
LEFT JOIN
(SELECT
usp.user_id, MAX(usp.id)AS id
FROM
user_subscription_plan AS usp
GROUP BY usp.user_id) AS subscription_plan ON subscription_plan.user_id = u.id;