如何编写查询以获得特殊价格(如果可用)

时间:2015-08-02 08:57:43

标签: mysql mysqli

我的表结构如下:

-- 1 price type.

   CREATE TABLE IF NOT EXISTS `price_type` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
    `type` varchar(50) NOT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `price_type` (`id`, `type`) VALUES
(1, 'Normal price'),
(2, 'Special price');

-- 2 Products

CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `product` (`id`, `name`) VALUES
(1, 'Tshirt'),
(2, 'Shirt'),
(3, 'Pants'),
(4, 'Pull over');

-- 3 Product price

CREATE TABLE IF NOT EXISTS `product_price` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `price_type_id` int(11) NOT NULL,
  `price` float NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `product_price` (`id`, `product_id`, `price_type_id`, `price`, `start_date`, `end_date`) VALUES
(1, 1, 1, 300, '0000-00-00', '0000-00-00'),
(2, 2, 1, 500, '0000-00-00', '0000-00-00'),
(3, 3, 1, 400, '0000-00-00', '0000-00-00'),
(4, 3, 2, 150, '2015-08-01', '2015-11-02'),
(5, 4, 1, 600, '0000-00-00', '0000-00-00');

预期结果(特殊时间段): enter image description here

产品(产品)价格存储在具有不同价格类型(price_type)ID的不同表格(product_price)中。

在这种情况下,产品裤子在2015-08-01和2015-11-02之间的特价150.00。所以它应该显示特价而不是正常价格400.00

我该如何为它编写查询?

2 个答案:

答案 0 :(得分:1)

您可以加入价格表两次,一次获得正常价格,一次(左加入)特价,如果有任何有效的今天。

在字段列表中,您可以使用coalesce获取特价,然后再回到正常价格。这样,您可以轻松地从查询中返回当前价格,无论其类型如何:

select  p.id as product_id,
        p.name,
        np.price as normal_price,
        sp.price as special_price,
        sp.end_date as special_price_end_date,

        coalesce(sp.price, np.price) as current_price
from  product p
inner join product_price np 
      on np.product_id = p.id
         and np.price_type_id = 1
left  join product_price sp 
      on sp.product_id = p.id
         and sp.price_type_id = 2
         and CURRENT_DATE() between sp.start_date and sp.end_date

答案 1 :(得分:1)

类似的东西:

SELECT pp.id, p.name, pp.price, pp.start_date, pp.end_date FROM product_price pp
INNER JOIN product p
ON pp.product_id=p.id
WHERE 
(pp.start_date < '2015-08-01' AND pp.end_date > '2015-08-01')
OR (pp.start_date IS NULL AND pp.end_date IS NULL)
GROUP BY p.name
ORDER BY pp.price_type_id DESC