使用默认行获取数据

时间:2017-01-17 10:39:40

标签: mysql

假设我们有表resourceitemprice

item
+--------+---------+
| itemId | name    |
+--------+---------+
|   2743 | Product |
+--------+---------+

resource
+------------------+-----+----------------+--+
|resourceId | key | value          | groupId |
+-----------+-----+----------------+---------+
|        45 |   1 | Client         |       3 |
|        46 |   2 | Manufacturer   |       3 |
|        69 |   1 | Delivery       |       4 |
|        70 |   2 | Collection     |       4 |
|        71 |   3 | Assembly       |       4 |
|        72 |   4 | Client Request |       4 |
|        73 |   1 | Draft          |       5 |
|        74 |   2 | Not Confirmed  |       5 |
|        75 |   3 | Confirmed      |       5 |
+-----------+-----+----------------+---------+

price
+---------+-----------+--------+----------+
| priceId | serviceId | itemId | price    |
+---------+-----------+--------+----------+
|     294 |         4 |      0 |  20.0000 |
|     293 |         3 |      0 |  20.0000 |
|     292 |         2 |      0 |  20.0000 |
|     291 |         1 |      0 |  20.0000 |
|     290 |         1 |   2743 |  18.4000 |
|     288 |         1 |   2738 |  10.0000 |
|     267 |         4 |   2721 |   0.0000 |
|     266 |         3 |   2721 |   0.0000 |
|     265 |         2 |   2721 |   0.0000 |
+---------+-----------+--------+----------+

groupId = 4的表资源中的行是服务。它们是通过表keyprice)中的列serviceId引用的。如您所见,我有这些服务的默认价格(price中的前四行itemId = 0)。我需要获取与给定项目的服务一样多的pirce行。如果该项目没有服务价格,则应提取服务的默认价格。例如,id = 2743的商品具有服务交付的价格。对于所有其他服务,应返回其默认价格。我需要的是这样的结果:

+---------+-----------+--------+----------+-----------+-----+----------------+---------+
| priceId | serviceId | itemId | price    |resourceId | key | value          | groupId |
+---------+-----------+--------+----------+-----------+-----+----------------+---------+
|     290 |         1 |   2743 |  18.4000 |        69 |   1 | Delivery       |       4 |
|     292 |         2 |   NULL |  17.0000 |        70 |   2 | Collection     |       4 |
|     293 |         3 |   NULL |  13.0000 |        71 |   3 | Assembly       |       4 |
|     294 |         4 |   NULL |   9.0000 |        72 |   4 | Client Request |       4 |
+---------+-----------+--------+----------+-----------+-----+----------------+---------+

这是我试过的查询。我获得了与服务一样多的行,但它们都具有相同的价格(项目的价格)

SELECT * 
  FROM `price` AS `p`
 INNER JOIN `item` ON p.id = item.id
 RIGHT JOIN `resource` AS `res` ON 1 = 1
 WHERE (res.groupId = 4)
   AND (p.itemId = 2743);

1 个答案:

答案 0 :(得分:0)

select i.itemId, coalesce(p1.price, p0.price)
from item i
cross join price p0
left  join price p1 
  on  p1.serviceId = p0.serviceId
  and p1.itemId    = i.itemId
where i.itemId  = 2743
  and p0.itemId = 0