如何连接或子查询表示层的表

时间:2013-12-14 20:31:24

标签: mysql sql join correlated-subquery

我有一个费用表,其中包含基于商品定价的价格截止列表中的费用。例如,第一个费用范围是价格为0美元的物品,而下一个等级的物品则需要1美元的费用。价格为25美元到下一层的物品有2美元的费用,等等。这是费用表:

Cutoff Fee
------ ---
0      1
25     2
100    3

这是物品表,价格为:

项目

Id     Price
------ ------
1      32
2      18
3      2
4      100

结果应如下所示:

期望物品费用结果

Id    Price   Fee     Total Price with fee
----- ------- ------- -----------
1     32      2       34
2     18      1       19
3     2       1       3
4     100     3       103

创建结果一直很具挑战性。以下是两个表之间的连接结果的笛卡尔积:

Id  Price   Cutoff  Fee
--- ------- ------- ---
1   32      0       1 -- eliminate because price is above the next cut 25
2   18      0       1
3   2       0       1
4   100     0       1 -- eliminate because price is above the next cut 25
1   32      25      2
2   18      25      2 -- eliminate because price is below this cut
3   2       25      2 -- eliminate because price is below this cut
4   100     25      2 -- eliminate because price is above (equal to) the next cut 100
1   32      100     3 -- eliminate because price is below this cut
2   18      100     3 -- eliminate because price is below this cut
3   2       100     3 -- eliminate because price is below this cut
4   100     100     3

第一个很简单:

where price >= cut

这将列表缩小为:

Id  Price   Cutoff  Fee
--- ------- ------- ---
1   32      0       1 -- eliminate because price is above the next cut 25
2   18      0       1
3   2       0       1
4   100     0       1 -- eliminate because price is above the next cut 25
1   32      25      2
4   100     25      2 -- eliminate because price is above (equal to) the next cut 100
4   100     100     3

以下是问题:如何过滤掉下一个定价层中的记录?这是我到目前为止的sql。

select price, cutoff, fee from item, fee
where price >= cutoff;

我尝试了一个子查询:

select price, cutoff, fee, 
    (select min(cutoff), fee from fee where cutoff > price) as nextfee 
from item, fee
where price >= cutoff;

但这会产生错误:

  

操作数应包含1个列

2 个答案:

答案 0 :(得分:2)

解决此问题的一种方法是使用相关子查询来获取fee表中截止值大于或等于价格的第一笔费用:

select id, price, fee, (price + fee) as totalprice
from (select id, price,
             (select fee
              from fee
              where price >= cutoff
              order by cutoff desc
              limit 1
             ) as fee
      from item
     ) i

答案 1 :(得分:0)

这个怎么样?没有子连接,更好的性能和更简单。

SELECT i.id, i.price, MAX(f.fee), i.price + MAX(f.fee) 
FROM item i INNER JOIN fee f
ON i.price > f.cutoff
GROUP BY i.id, i.price