查询几个表数据,根据存在情况,插入到另一个表中

INSERT INTO now_pay_cust_stat (
    customer_id,
    n_p_custid,
    sum_offer_order,
    sum_offer_pay,
    sum_product_order,
    sum_product_pay
) SELECT
    a.custid,
    a.id,
    sum(b.order_money),
    sum(b.real_money),
    sum(c.total_price),
    sum(c.real_price)
FROM
    now_pay_cust a
LEFT JOIN now_pay_orders b ON a.id = b.n_p_custid
AND a.custid = b.custid
AND b.isvalid = TRUE
LEFT JOIN now_pay_product_orders c ON a.id = c.np_customer_id
AND a.custid = c.customer_id
AND c.isvalid = TRUE
WHERE
    a.isvalid = TRUE
AND NOT EXISTS (
    SELECT
        id
    FROM
        now_pay_cust_stat
    WHERE
        n_p_custid = a.id
    AND customer_id = a.custid
)
GROUP BY
    a.id

你可能感兴趣的:(MySQL)