SQL价格计划,选择上一个时间戳,即<= UTC_TIMESTAMP()

时间:2018-07-06 20:40:43

标签: mysql sql mysqli

我有一个名为product_pricing的表。

在这里,我可以为每个ID添加多个价格。它们与众不同的地方是product_pricingtimestamp_valid ...这是我用来预先安排价格变动的工具。

    SELECT 
        `products`.`wo_id`,
        `products`.`fty_id`,
        `products`.`price` AS price1,

        `product_attributes`.`fty_id`,
        `product_attributes`.`cat_id`,
        `product_attributes`.`design_id`,
        `product_attributes`.`season_id`,

        `products_u_ids`.`u_id`,
        `products_u_ids`.`link_id`,

        `product_designs`.`design_id`,
        `product_designs`.`brand_id`,

        COALESCE(`product_pricing`.`u_id`, NULL) AS price2_u_id,
        COALESCE(`product_pricing`.`currency`, NULL) AS price2_currency,
        COALESCE(`product_pricing`.`price`, NULL) AS price2,
        COALESCE(`product_pricing`.`formula_id`, NULL) price2_formula_id,
        COALESCE(`product_pricing`.`vat_calculated`) AS price2_vat_calculated,
        COALESCE(`product_pricing`.`vat_id`, NULL) AS price2_vat_id,
        COALESCE(`product_pricing`.`timestamp_valid`, NULL) price2_timestamp_valid, 

        COALESCE(`product_price_formulas`.`formula_id`, NULL) AS price2_formula_id,
        COALESCE(`product_price_formulas`.`formula`, NULL) AS price2_formula,

        COALESCE(`global_vat_tariffs`.`vat_id`, NULL) AS price2_vat_id,
        COALESCE(`global_vat_tariffs`.`percentage`, NULL) AS price2_vat_tariff

    FROM `products`

    LEFT JOIN `product_attributes`
        ON `products`.`fty_id` = `product_attributes`.`fty_id`

    LEFT JOIN `products_u_ids`
        ON `product_attributes`.`fty_id` = `products_u_ids`.`link_id`

    LEFT JOIN `product_designs` 
        ON `product_attributes`.`design_id` = `product_designs`.`design_id`

    LEFT JOIN `product_pricing`
        ON `products_u_ids`.`u_id` = `product_pricing`.`u_id`

    LEFT JOIN `product_price_formulas` 
        ON `product_pricing`.`formula_id` = `product_price_formulas`.`formula_id`

    LEFT JOIN `global_vat_tariffs` 
        ON `product_pricing`.`vat_id` = `global_vat_tariffs`.`vat_id`

         LEFT OUTER JOIN (
            SELECT `product_pricing`.`u_id`, MAX(`timestamp_valid`) AS MaxDate
            FROM `product_pricing`
            WHERE `product_pricing`.`timestamp_valid` <= UTC_TIMESTAMP
            GROUP BY `product_pricing`.`u_id`
        ) AS temp ON temp.u_id = `product_pricing`.`u_id` AND temp.MaxDate = `product_pricing`.`timestamp_valid`

    WHERE `products`.`wo_id` IN ('028284', '018305', '031536')

上面的SQL会返回给定ID的所有行,而不仅仅是返回product_pricingtimestamp_valid``<= UTC_TIMESTAMP()

LEFT OUTER JOIN中存在问题。

此SQL要做的另一件事是,当没有为price2设置任何内容时,它不应破坏脚本,而只需为price2返回NULL。我通过使用COALESCE来解决这个问题。

这就是我得到的:

enter image description here

这是我应该得到的: enter image description here

假设查询日期为2018-5-7。

有什么想法可以使用LEFT OUTER JOIN解决此问题吗?

1 个答案:

答案 0 :(得分:0)

您正在包含您提到的时间戳过滤器的子查询上使用LEFT JOIN操作。 LEFT JOIN保留不符合其ON条件的行。您可以在该子查询上尝试普通的INNER连接;内部JOIN不会保留符合ON条件的行。