0

我看到了这个问题的变体,但它们要么不适用,要么我不明白答案。

我有两张桌子,一张是收费类型,另一种是收费。我想加入他们以获得适当的价值。我想加入费用在 startDate 和 endDate 之间以及类型上的表格。如果没有匹配项,我希望它选择类型 -1(日期条件相同)。如果没有匹配,我不希望它出现在结果中。

我最初打算做一个按“type” desc 排序的普通左连接,然后按“type”分组,相信它只会让我使用第一种类型,但我读到 MySQL 建议不要这样做,因为 group by 可能是不可预测的并不总是返回第一场比赛。

表:

startDate | endDate  | type | addCost
--------------------------------------
2010-01-01 2010-12-31  1     100
2010-01-01 2010-12-31  2     200
2010-01-01 2010-12-31 -1      50
2011-01-01 2012-02-20  3     350
2011-01-01 2012-02-20  1     150
2011-01-01 2012-02-20 -1      75


chargeDate | type | cost
---------------------------
2010-10-01  1     10
2010-11-01  2     20
2010-12-01  4     40
2011-02-01  3     60
2011-03-01  2     25
2011-04-01  4     25

期望的结果:

chargeDate | type | cost | addCost
---------------------------------
2010-10-01  1     10     100
2010-11-01  2     20     200 
2010-12-01  4     40      50
2011-02-01  3     60     350
2011-03-01  2     25      75
4

1 回答 1

1

我正在使用我试图加入的子charges查询charges_types。如果连接不成功,typeis nulland with coalesceI 设置type_c-1,否则我设置为type. 然后我charges_types再次加入这个子查询,并在加入子句上我使用type_c而不是type

select c.chargeDate, c.type, c.cost, ct.addCost
from
  (select
     charges.chargeDate,
     charges.type,
     coalesce(charges_types.type, -1) as type_c,
     charges.cost
   from
     charges left join charges_types
     on charges.chargeDate between charges_types.startDate and charges_types.endDate
       and charges.type = charges_types.type) c
  inner join charges_types ct
  on c.chargeDate between ct.startDate and ct.endDate
     and c.type_c = ct.type
于 2012-12-07T14:52:54.487 回答