You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询问题:获取master_account数据及关联affiliate_partners状态

问题:查询关联账号的合作状态

需求

以account_id = 3067261登录,需查询master_account表中除自身外的所有账号数据,同时获取这些账号与当前账号在affiliate_partners表中关联的is_client、is_driver状态,仅当账号未关联时返回null。

现有表结构及数据

master_account表

_idaccount_id
13067261
24327735
38521420

affiliate_partners表

_idaccount_idpartner_account_idis_clientis_driver
130672614327735truetrue
243277353067261truetrue
385214204327735falsefalse

尝试的SQL及问题

尝试的查询语句:

SELECT 
        ma._id,
        ma.account_id, 
        CASE 
        WHEN ma.account_id = '3067261'
        THEN ap.is_client
        ELSE null
        END as is_client,
        CASE 
        WHEN ma.account_id = '3067261'
        THEN ap.is_driver
        ELSE null
        END as is_driver
from master_account ma
left join affiliate_partners ap
on ma.account_id = ap.account_id
where ma.account_id != '3067261'

实际结果:所有is_client和is_driver均为null

_idaccount_idis_clientis_driver
24327735nullnull
38521420nullnull

预期结果:

_idaccount_idis_clientis_driver
24327735truetrue
38521420falsefalse

修正后的SQL及解释

1. 符合“获取与当前账号关联状态”的需求

原查询的核心问题:

  • CASE逻辑完全错误:WHERE条件已排除当前账号,WHEN ma.account_id = '3067261'永远不会触发,导致所有结果返回null
  • 关联条件偏差:仅关联账号自身的合作记录,未匹配当前账号与目标账号的双向合作关系

修正后的SQL:

SELECT 
    ma._id,
    ma.account_id,
    ap.is_client,
    ap.is_driver
FROM master_account ma
LEFT JOIN affiliate_partners ap
    -- 匹配当前账号与目标账号的双向合作记录
    ON (ap.account_id = '3067261' AND ap.partner_account_id = ma.account_id)
    OR (ap.partner_account_id = '3067261' AND ap.account_id = ma.account_id)
WHERE ma.account_id != '3067261';

此查询返回结果:

_idaccount_idis_clientis_driver
24327735truetrue
38521420nullnull

完全符合“仅当账号未与当前账号关联时返回null”的需求。

2. 匹配你给出的预期结果(取账号自身合作状态)

若预期结果是实际需要的,说明需求为获取目标账号在affiliate_partners中的任意合作状态,此时只需移除错误的CASE逻辑即可:

SELECT 
    ma._id,
    ma.account_id,
    ap.is_client,
    ap.is_driver
FROM master_account ma
LEFT JOIN affiliate_partners ap
    ON ma.account_id = ap.account_id
WHERE ma.account_id != '3067261';

该查询会直接关联目标账号的合作记录,得到你给出的预期结果。

内容的提问来源于stack exchange,提问作者Deep Mandal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:15:30