与多个嵌套选择的左联接

时间:2018-12-18 16:10:29

标签: mysql sql join

以下语句出人意料地有效,但是我不确定3次加入同一张表是否有效。我必须禁用ONLY_FULL_GROUP_BY才能使其正常工作。

比赛中有2张桌子。一个是带有分发者信息的主表,第二个是一个购买表,其中包含主表(assoc)中关联分发者的amountdateid。 / p>

我需要三件事。年初至今的销售额,该总额表示某个分销商从当年起的销售额。去年的销售额,与上一年相同。然后,最后只需获取最新的购买日期和金额即可。

用户需要能够通过这些值(lysytd等)进行过滤,因此将它们作为变量连接似乎是一种方法。数据库大小约为7,000条记录。

SELECT 
    d.*,
    ytd_total,
    lys_total,
    last_amount,
    last_purchase

FROM Distributor as d
LEFT JOIN (
    SELECT
        assoc, SUM(amount) ytd_total
        FROM purchases
        WHERE db = 1 AND purchase_date >= '{$year}-01-01'
        GROUP BY assoc
) AS ytd
ON ytd.assoc = d.id

LEFT JOIN (
    SELECT
        assoc, SUM(amount) lys_total
        FROM purchases
        WHERE db = 1 AND purchase_date BETWEEN '{$lyear}-01-01' AND '{$lyear}-12-31'
        GROUP BY assoc
) AS lys
ON lys.assoc = d.id

LEFT JOIN (
    SELECT
        assoc, amount last_amount, purchase_date last_purchase
        FROM purchases
        WHERE db = 1
        GROUP BY assoc
) AS lst
ON lst.assoc = d.id

WHERE ........

1 个答案:

答案 0 :(得分:0)

您可以在每个聚合查询中做更多的工作。我认为这更是您想要的:

select d.*, pa.ytd_total, pa.lys_total, pa.last_purchase_date, p.amount
from distributor d left join
     (select p.assoc,
             sum(case when p.purchase_date >= '{$year}-01-01' then p.amount end) as ytd_total,
             sum(case when p.purchase_date BETWEEN '{$lyear}-01-01' AND '{$lyear}-12-31' then p.amount end) as lys_total,
             max(p.purchase_date) as last_purchase_date             
      from purchases p
      where p.db = 1
      group by p.assoc
     ) pa left join
     purchases p
     on pa.assoc = p.assoc and pa.last_purchase_date = p.purchase_date;