MySQL Left Join:如果主要条件不存在,则使用备份条件只返回一个

时间:2012-12-07 14:04:57

标签: mysql join

我已经看到了这个问题的变化,但要么他们不适用,要么我不理解答案。

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

我最初是打算按'type'desc命令进行正常的左连接,然后按'type'分组,认为它只会留给我第一种类型,但我读到MySQL建议不要这样做,因为该组由可能无法预测,并不总是返回第一场比赛。

表:

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

1 个答案:

答案 0 :(得分:1)

我正在使用子查询,我正在尝试将charges加入charges_types。如果加入不成功,typenullcoalesce我将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