我已经看到了这个问题的变化,但要么他们不适用,要么我不理解答案。
我有两张桌子,其中一张桌子有收费类型,附加费用和一项收费。我想加入他们以获得适当的值。我想加入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
答案 0 :(得分:1)
我正在使用子查询,我正在尝试将charges
加入charges_types
。如果加入不成功,type
为null
,coalesce
我将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