希望你们都做得很好!
我正在尝试使用多个连接在表上运行批量更新,但我无法这样做。
我有3张桌子:
表1:items
|id|total_price|created_at|
表2:prices
|id|company_id|item_id|special_price|created_at|
________________________________________________
| 1| 1 | 100 | 20.0 | 2017-01-01|
| 2| 1 | 101 | 30.0 | 2017-01-01|
| 3| 1 | 102 | 70.0 | 2017-01-01|
| 4| 1 | 103 | 90.0 | 2017-01-01|
表3:ranges
|id|company_id|range_from|range_to|commission_percent|
______________________________________________________
| 1| 1 | 10.0 | 50.0 | 5.0 |
| 2| 1 | 51.0 | 100.0 | 10.0 |
结束我想要实现的结果:我想基于以下SQL批量更新prices
表:
UPDATE prices
SET special_price = (
CASE
WHEN (special_price BETWEEN ranges.range_from AND ranges.range_to) AND prices.company_id = ranges.company_id
THEN
ROUND((special_price + (special_price * commission_percent / 100)), 2)
ELSE
special_price
END
)
FROM ranges
WHERE prices.company_id = 1
结果如下:
|id|company_id|item_id|special_price|created_at|
________________________________________________
| 1| 1 | 100 | 21.0 | 2017-01-01|
| 2| 1 | 101 | 31.5 | 2017-01-01|
| 3| 1 | 102 | 77.0 | 2017-01-01|
| 4| 1 | 103 | 99.0 | 2017-01-01|
到目前为止我遇到的限制:
IMP 我将在prices
表
请帮助/建议!
答案 0 :(得分:0)
我能够通过以下SQL来解决这个问题:
UPDATE prices
SET special_price = ROUND((special_price + (special_price * ranges.commission_percent / 100)), 2)
FROM items, ranges
WHERE (prices.special_price BETWEEN ranges.range_from AND ranges.range_to)
AND prices.company_id = ranges.company_id
AND prices.stock_item_id = items.id AND prices.special_price = items.total_price
AND prices.company_id = 'XX';
使用此SQL的优点是: