我有2个表,定义如下:
CREATE TABLE `product` (
`pid` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR( 50 ) NOT NULL,
`description` TEXT,
`qty` SMALLINT( 5 ) UNSIGNED NOT NULL DEFAULT '0',
`category` ENUM( '1', '2', '3', '4', '5', '6', '7', '8' ) NOT NULL DEFAULT '1',
`price` DECIMAL( 7, 2 ) UNSIGNED NOT NULL
) ENGINE = InnoDB;
CREATE TABLE `discount` (
`did` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`pid` SMALLINT( 5 ) UNSIGNED NOT NULL,
`sDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`eDate` DATETIME NOT NULL,
`dPrice` DECIMAL( 7, 2 ) UNSIGNED NOT NULL,
FOREIGN KEY ( `pid` ) REFERENCES `product`(`pid`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB;
我正在尝试为每个产品和
NULL
dPrice或dPrice(如果有带有sDate < NOW()
和eDate > NOW()
的折扣条目)正好得到1行的结果。我试过了:
select p.pid, name, price, dPrice, qty
from product p left join discount d
on p.pid = d.pid
where d.sDate<now() and d.eDate>now();
问题在于它只退回具有有效折扣的产品。没有折扣或过期/将来折扣的产品不会显示。
接下来我尝试了:
select p.pid, name, price, dPrice, qty
from product p left join discount d
on p.pid = d.pid
where (d.sDate<now() and d.eDate>now()) or dPrice is null;
这比我期望的结果接近了1步,它列出了具有有效折扣的产品和没有折扣的产品,但是我仍然缺少定义了过期/将来折扣的产品。
在PHP中可以随时检查只有1个折扣处于活动状态,并且不需要包含在此语句中。任何帮助深表感谢!
最佳答案
select p.pid, name, price, dPrice, qty
from product p
left join discount d on p.pid = d.pid and d.sDate<now() and d.eDate>now()
比子查询更有效和更“标准”。