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

我有两张桌子的订单

id  article amount
1   1       1               
2   2       50              

和价格

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    

价格表包含物品的ID和您为获得批量折扣而必须购买的最低金额(这将改变订单的价格).我想将价格加入订单,结果如下:

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

最佳答案 您需要的查询是:

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

点赞