0

この質問のバリエーションを見たことがありますが、それらは当てはまらないか、答えがわかりませんでした。

2 つのテーブルがあり、1 つのテーブルには、追加料金のある料金タイプと料金の 1 つがあります。それらに参加して、適切な値を取得したいと思います。料金が 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
4

1 に答える 1

1

に参加しようとしているサブクエリを使用してchargescharges_typesます。結合が成功しない場合typenull、 を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
于 2012-12-07T14:52:54.487 に答える