mysql 使用select插入多条数据,insert into (1,2,3,4,)select(1,2,3,4)

 SET @yesterday = CURDATE() - INTERVAL n DAY; # 前N天的日期,n通常为1,即昨天

    INSERT IGNORE mob_report.day_coupon_report (
        mdate, 
        id, 
        day_release_coupon_count,
        day_writeoff_coupon_count,
        shop_id,
        shop_name,
        coupon_id,
        coupon_name,
        day_shop_release_coupon_count,
        day_shop_writeoff_coupon_count,
        create_time)
    SELECT 
        @yesterday, 
        NULL,
        (SELECT COUNT(1) FROM mob_coupon.member_receive_coupon nrc WHERE @yesterday = DATE(FROM_UNIXTIME(nrc.create_time))), # 查询前N天优惠券发放总数
        (SELECT COUNT(1) FROM mob_coupon.writeoff_coupon_record wcr WHERE @yesterday = DATE(FROM_UNIXTIME(wcr.create_time))), # 查询前N天优惠券核销总数
        tmp.shop_id,
        tmp.shop_name,
        tmp.coupon_id,
        tmp.coupon_name,
        tmp.day_shop_release_coupon_count,
        tmp.day_shop_writeoff_coupon_count,
        UNIX_TIMESTAMP(NOW())
    FROM (
        # 查询前N天按优惠券分组的发放数量,核销数量
        SELECT
            SUM(day_shop_release_coupon_count) AS day_shop_release_coupon_count,
            SUM(day_shop_writeoff_coupon_count) AS day_shop_writeoff_coupon_count,
            coupon_id,
            `name` AS coupon_name,
            shop_id,
            shop_name
        FROM (
            # 查询前N天按优惠券分组的发放数量,每组核销数量作为0
            SELECT 
                COUNT(1) AS day_shop_release_coupon_count,
                0 AS day_shop_writeoff_coupon_count,
                coupon_id,
                b.name,
                b.shop_id,
                c.shop_name
            FROM mob_coupon.member_receive_coupon a
            LEFT JOIN mob_coupon.coupon_info b ON a.coupon_id = b.id 
            LEFT JOIN mob_base_info.shop_info c ON b.shop_id = c.id
            WHERE @yesterday = DATE(FROM_UNIXTIME(a.create_time))
            GROUP BY a.coupon_id
            UNION ALL
            # 查询前N天按优惠券分组的核销数量,每组发放数量作为0
            SELECT 
                0 AS day_shop_release_coupon_count,
                COUNT(1) AS day_shop_writeoff_coupon_count,
                coupon_id,
                b.name,
                b.shop_id,
                c.shop_name
            FROM mob_coupon.writeoff_coupon_record a
            LEFT JOIN mob_coupon.coupon_info b ON a.coupon_id = b.id 
            LEFT JOIN mob_base_info.shop_info c ON b.shop_id = c.id
            WHERE @yesterday = DATE(FROM_UNIXTIME(a.create_time))
            GROUP BY a.coupon_id
        ) t
        GROUP BY t.coupon_id
    ) tmp;

你可能感兴趣的:(数据库)