我有2個表,這樣定義:SQL加入該顯示器左表即使右表不匹配,其中
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;
我試圖得到完全排1的結果爲每一個產品和一個NULL
dPrice或dPrice是否有sDate < NOW()
和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();
的問題,這是它僅返回產品具有有效的折扣。沒有折扣或過期/未來折扣的產品不顯示。
接下來我想:
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步步接近我想要的結果,在這裏上市的產品有合法的折扣和產品沒有折扣,但我仍然失蹤過期/未來產品折扣定義。
檢查在任何時候只有1個折扣處於活動狀態是在PHP中完成的,不需要包含在本聲明中。任何幫助深表感謝!
什麼數據庫系統?什麼版本? – 2009-12-10 22:13:18