MySQL从其他表加入下一个较低的值

时间:2015-12-04 00:37:58

标签: mysql join

我有两张表orders

id  article amount
1   1       1               
2   2       50              

prices

id  article min_amount  price
1   1       1           42.99   
2   2       1           5.06    
3   2       5           4.55    
4   2       10          4.3     
5   2       25          4.05    
6   2       100         2.66    

prices表包含文章的ID以及为获得批量折扣而必须购买的最低金额(这将改变订单的价格)。我想将prices加入orders,以便结果如下:

id  article amount  price
1   1       1       42.99
2   2       50      4.05

订单ID 2高于最小值(25)以获得4.05€的文章,但仍低于100,您将获得更大的折扣,因此查询将选择下一个较低的值。

到目前为止,我已尝试过此查询

SELECT 
    orders.id AS id,
    orders.article,
    orders.amount,
    prices.price,
    (orders.amount - prices.min_amount) AS discount_diff
FROM orders
LEFT JOIN prices ON (prices.article = orders.article) AND (prices.min_amount <= orders.amount)

给出了这个结果

id  article amount  price   discount_diff
1   1       1       42.99   0
2   2       50      5.06    49
2   2       50      4.55    45
2   2       50      4.3     40
2   2       50      4.05    25 

你可以在“js”小提琴上找到这个例子:http://sqlfiddle.com/#!9/1b2bf/8

1 个答案:

答案 0 :(得分:1)

您需要的查询是:

SELECT orders.id AS id,
       orders.article,
       orders.amount,
       prices.price
  FROM orders
         INNER JOIN prices ON ( prices.article = orders.article
                                and prices.min_amount <= orders.amount)
         INNER JOIN ( SELECT orders.article,
                             orders.amount,
                             min(prices.price) minprince
                        FROM orders
                               INNER JOIN prices ON (prices.article = orders.article
                                                   AND prices.min_amount <= orders.amount)
                       GROUP BY orders.article,
                                orders.amount) b
                ON (     prices.article = b.article
                    AND orders.amount = b.amount
                    AND prices.price = b.minprince) 

请在此处查看:http://sqlfiddle.com/#!9/1b2bf/27