简体   繁体   English

在子查询中使用联接?

[英]Using a join within a sub query?

The following query is returning all affiliate_id 's where the amount owed is more than 50. 以下查询将返回所有欠款超过50的affiliate_id

        SELECT
            t1.affiliate_id
        FROM
        (
            SELECT affiliate_id, SUM(payout) AS payout_total
            FROM exp_cdwd_aff_purchases
            GROUP BY affiliate_id
        ) t1
        LEFT JOIN
        (
            SELECT affiliate_id, SUM(amount_paid) AS amount_paid_total
            FROM exp_cdwd_aff_payments
            GROUP BY affiliate_id
        ) t2
            ON t1.affiliate_id = t2.affiliate_id
        WHERE t1.payout_total > COALESCE(t2.amount_paid_total, 0) + 50

I need to also return an email address for each affiliate_id from the table exp_member_data . 我还需要为表exp_member_data每个affiliate_id返回一个电子邮件地址。 The affiliate_id can be referenced against member_id . 可以针对member_id引用affiliate_id

I had thought the following may work, but it doesn't. 我曾以为以下方法可能有效,但事实并非如此。 Can anyone explain how I can get this result? 谁能解释我如何得到这个结果?

        SELECT
            t1.affiliate_id, t1.m_field_id_26
        FROM
        (
            SELECT af.affiliate_id, SUM(af.payout) AS payout_total, md.m_field_id_26
            FROM exp_cdwd_aff_purchasesAS af
            LEFT JOIN exp_member_data AS md.member_id = af.affiliate_id
            GROUP BY affiliate_id
        ) t1
        LEFT JOIN
        (
            SELECT affiliate_id, SUM(amount_paid) AS amount_paid_total
            FROM exp_cdwd_aff_payments
            GROUP BY affiliate_id
        ) t2
            ON t1.affiliate_id = t2.affiliate_id
        WHERE t1.payout_total > COALESCE(t2.amount_paid_total, 0) + 50

If I read your query correctly, then the easiest thing to do would be to just add another join to the end to bring in the email address. 如果我正确地阅读了您的查询,那么最简单的方法就是在末尾添加另一个连接以引入电子邮件地址。 Something like this: 像这样:

SELECT
    t1.affiliate_id,
    COALESCE(t3.m_field_id_26, 'email is NA') AS m_field_id_26
FROM
(
    SELECT affiliate_id, SUM(payout) AS payout_total
    FROM exp_cdwd_aff_purchases
    GROUP BY affiliate_id
) t1
LEFT JOIN
(
    SELECT affiliate_id, SUM(amount_paid) AS amount_paid_total
    FROM exp_cdwd_aff_payments
    GROUP BY affiliate_id
) t2
    ON t1.affiliate_id = t2.affiliate_id
LEFT JOIN exp_member_data t3
    ON t1.affiliate_id = t3.member_id
WHERE t1.payout_total > COALESCE(t2.amount_paid_total, 0) + 50

Doing the join inside your aggregation query, as you currently have it, probably isn't ideal because that subquery exists to tally things, not to include email address information. 正如您目前所拥有的那样,在聚合查询中进行联接可能并不理想,因为该子查询的存在是为了统计事物,而不包括电子邮件地址信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM