我的表结构如下:
-- 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');
产品(product)价格存储在具有不同价格类型(price_type)id的不同表(product_price)中。
在这种情况下,产品裤子在 2015-08-01 和 2015-11-02 之间有特价 150.00。所以它应该显示特价而不是正常价格 400.00
如何为其编写查询?
最佳答案
您可以加入价格表两次,一次获取正常价格,一次(左加入)获取特价(如果有当天有效的价格表)。
在字段列表中,您可以使用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
关于mysql - 如何编写查询以获得特价(如果有),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770234/