我有兩個表如何從一個連接表
Products
id, name, last_updated
1, Computer table, 2014-07-20 09:00:00
2, Fruits basket, 2014-07-21 09:00:00
3, Hard Disk, 2014-07-22 09:00:00
Products_prices
id, product_id, min_price, max_price, description
1, 1, 10.00, 20.00, glass top
2, 1, 40.00, 80.00, hard wood
3, 1, 5.00, 10.00, pvc
4, 2, 15.00, 30.00, Mangoes only
5, 3, 30.00, 60.00, 1 TB
6, 3, 45.00, 90.00, 2 TB
7, 3, 20.00, 40.00, 500 GB
我需要檢索信息,如下
product.id, product.name, product_prices.min_price, product_prices.max_price, price_diff_percentage (calculated as round((max_price-min_price)/max_price*100))
如果我做一個LEFT通過MySQL查詢檢索分鐘價格JOIN例如
SELECT *, round((max_price-min_price)/max_price*100) price_diff_pct
FROM products p LEFT JOIN Product_prices pp on pp.product_id = p.id
然後我得到所有產品價格行的產品清單,例如,
1, computer table, 10.00, 20.00, 50, glass top
1, computer table, 40.00, 80.00, 50, hard wood
1, computer table, 5.00, 10.00, 50, pvc
2, fruits basket, 15.00, 30.00, mangoes only
3, hard disk, 30.00, 60.00, 50 1 TB
3, hard disk, 45.00, 90.00, 50 2 TB
3, hard disk, 20.00, 40.00, 50 500 GB
我希望它改成是用最低的最低報價和price_diff_pct例如返回一個產品行而不是上述返回集返回以下
1, computer table, 5.00, 10.00, 50, pvc
2, fruits basket, 15.00, 30.00, mangoes only
3, hard disk, 20.00, 40.00, 50 500 GB
而且我需要由last_updated日期排序。
我該如何解決這個問題?
UPDATE:
create table products (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(300) NOT NULL,
`last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
INSERT INTO products (1, 'Computer table', '2014-07-20 09:00:00');
INSERT INTO products (2, 'Fruits basket', '2014-07-21 09:00:00');
INSERT INTO products (3, 'Hard Disk', '2014-07-22 09:00:00');
CREATE TABLE IF NOT EXISTS `product_prices` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) unsigned NOT NULL,
`min_price` float(10,2) NOT NULL,
`max_price` float(10,2) NOT NULL,
`description` varchar(300) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO product_prices (1, 1, '10.00', '20.00', 'glass top');
INSERT INTO product_prices (2, 1, '40.00', '80.00', 'hard wood');
INSERT INTO product_prices (3, 1, '5.00', '10.00', 'pvc');
INSERT INTO product_prices (4, 2, '15.00', '30.00', 'Mangoes only');
INSERT INTO product_prices (5, 3, '30.00', '60.00', '1 TB');
INSERT INTO product_prices (6, 3, '45.00', '90.00', '2 TB');
INSERT INTO product_prices (7, 3, '20.00', '40.00', '500 GB');
如果你喜歡,可以考慮下列行爲這個簡單的兩步過程:1.如果您還沒有這樣做的話(你沒有),提供適當的DDL(和/或sqlfiddle),以便我們可以更容易地複製問題。 2.如果您尚未這樣做(您有),請提供與步驟1中提供的信息相對應的所需結果集。 – Strawberry
我已經提供瞭如上表結構和所需結果集的信息。請看看上面的內容。對不起,如果它不明確。讓我嘗試SQLFiddle – TigerTiger