与多个嵌套选择的左联接

与多个嵌套选择的左联接

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

有2张桌子在玩。一个是包含分销商信息的主表,第二个是购买表,其中包含主表(assoc)中关联的分销商的amountdateid

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

用户需要能够按这些值(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 ........

最佳答案

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

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;

关于mysql - 与多个嵌套选择的左联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53836996/

10-08 21:18