2011-05-02 160 views
0

大師!我被卡住了。目錄項目的價格取決於其數量。這裏的表格的例子:用mysql查詢計算價格

items: just item definitions 
------------------------- 
item_id | item_title 
------------------------- 
1  | "sample item" 
2  | "another item" 

items_prices: prices dependent to item quantity. 
       Less price taken for more quantity of item 
---------------------------- 
item_id | quantity | price 
---------------------------- 
1  | 1   | 100 
1  | 5   | 80 
1  | 10  | 60 
2  | 1   | 120 
2  | 3   | 100 

cart 
------------------- 
item_id | quantity 
------------------- 
1  | 20 
2  | 2 

是否有可能通過單個查詢獲得當前購物車的成本?

+2

如果'items_prices'具有'min_quantity'和'max_quantity',會更容易。 – 2011-05-02 22:53:30

+0

哦! min_quantity =我的例子中的數量。 – 2011-05-02 23:02:23

+0

是的,我明白了。添加一個'max_quantity'字段將使你想要的查詢真的相對容易,儘管它可能會複製數據。 (我說「可能」,因爲它也會讓你選擇不允許某些數量值,這可能是有用的。) – 2011-05-02 23:03:12

回答

1
select sum(x.totalcost) 
from (
    select c.item_id, c.quantity * ip.price as totalcost 
    from cart c 
    join items_prices ip 
     on c.item_id = ip.item_id 
    left join items_prices ip2 
     on ip2.quantity > ip.quantity 
     and c.quantity >= ip2.quantity 
    where c.quantity >= ip.quantity 
     and ip2.quantity is null 
) x 

的加入放回items_price再次讓我們過濾掉任何情況下,有這仍然符合我們的標準,更大的量。這應該越來越接近我們之後的東西

+0

怎麼可以這兩個:'.... ip2.quantity> = ip.quantity和ip2.quantity爲null'都是正確的? – Johan 2011-05-02 23:24:39

+0

左連接的行爲合理,但不是我的預期。 – afranz409 2011-05-02 23:33:06

+0

一個最終的編輯;需要擺脫限制條款,並不需要按順序的任何更長的時間,我已經驗證了這一點,並得到1440,這看起來是正確的 – afranz409 2011-05-02 23:46:34

0

對於項目編號1 23數量:

$item_id = 1; 
$quantity = 23; 

$sql = 'SELECT price * '.$quantity.' 
    FROM items_prices 
    WHERE item_id = '.$item_id.' 
     AND quantity <= '.$quantity.' 
    ORDER BY quantity DESC 
    LIMIT 1'; 
+0

-1語法錯誤:應該用''''括起來,逗號缺失。問題在於當前的購物車成本,顯然是使用購物車中的數據,而不是常量 – Johan 2011-05-02 23:05:00

+0

@Johan:逗號的_what_是誰失蹤了?誰是逗號,無論如何? – 2011-05-02 23:18:16

+0

@Tomalak:','<---- – Johan 2011-05-02 23:20:49