私はSQLを書く初心者であり、以下に示すように3つのテーブルで作業するためのレガシーシステムを手元に持っています:
Table A
=========
id | tracker_id | created_on | status | p_id
1 | 1 | ... | (Table C latest new_val ) 4 | 121
Table B
=========
id | a_id | created_on |
1 | 1 | 2013-12-12 15:15:16
2 | 1 | 2013-12-15 15:20:16
3 | 1 | 2013-12-15 15:25:16
4 | 1 | 2013-12-15 15:30:16
5 | 1 | 2013-12-15 16:20:16
6 | 1 | 2013-12-16 17:20:16
7 | 1 | 2013-12-25 16:25:16
Table C
=========
id | b_id | type | old_val | new_val
1 | 1 | type1| 1 | 2
2 | 2 | type1| 2 | 3
3 | 3 | type1| 3 | 4
4 | 4 | type1| 4 | 5
5 | 5 | type1| 5 | 3
6 | 6 | type1| 3 | 5
7 | 7 | type1| 5 | 3
2013-12-13 と 2013-12-17 という特定の日付の間のテーブル A id の数を、その時間範囲の間のテーブル C new_val の特定の最新値で取得したいので、上記の場合、「2013 -12-13 and 2013-12-17" p_id が 121 で、テーブル C の new_val が 5 の場合、 1 を取得する必要があります。また、テーブル C new_val を 3 として「2013-12-13 と 2013-12-17」の間でクエリを実行すると、 0 を取得する必要があります。
私はフォームのクエリを書きました
Select count(tableA.id) from tableA tableA
inner join tableB tableB on tableA.id=tableB.a_id
inner join tableC tableCdetails on tableB.id=tableCdetails.b_id
where tableCdetails.type = 'type1' and tableCdetails.new_val='5'
and tableB.created_on between '2013-12-13' AND '2013-12-17'
and tableA.p_id = 121
試行錯誤の方法を使用していくつかの組み合わせを試しましたが、特定の場合に上記のクエリで特定の値を取得していますが、これはシステム内の他の値と一致しません。時間範囲の最新の tableB id を取得し、その tableB id に対応する tableC エントリの new_val と一致させる必要があるという事実を見逃していると思いますが、残念ながらそれを取得する方法がわかりません。誰かが上記のクエリまたは他のアプローチでそれを行う方法を教えてもらえますか (または、クエリを完全に間違った方法で実行しています)。