###前提・実現したいこと
以下のようなテーブルからexaminee_idとsurvey_idのペアでの最新のanswerの値を取得したいのですが、cakePHPとしてどのようにコードを記載したら良いのか分かりません。ご教授お願いします!
id | examinee_id | survey_id | answer | starttime |
---|---|---|---|---|
18 | 1 | 23 | 1 | 2017-06-30 13:55:57 |
19 | 1 | 18 | 2 | 2017-06-30 14:00:22 |
20 | 1 | 18 | 2 | 2017-06-30 14:07:20 |
21 | 1 | 18 | 1 | 2017-06-30 14:07:40 |
22 | 1 | 18 | 2 | 2017-06-30 16:25:20 |
23 | 1 | 19 | 1 | 2017-06-30 16:25:22 |
24 | 1 | 20 | 0 | 2017-06-30 16:25:26 |
25 | 1 | 30 | 2 | 2017-06-30 16:34:15 |
26 | 1 | 30 | 3 | 2017-06-30 18:00:59 |
27 | 1 | 31 | 0 | 2017-06-30 18:01:17 |
28 | 1 | 18 | 2 | 2017-07-01 18:29:48 |
###期待される取得結果
id | examinee_id | survey_id | answer | starttime |
---|---|---|---|---|
18 | 1 | 23 | 1 | 2017-06-30 13:55:57 |
23 | 1 | 19 | 1 | 2017-06-30 16:25:22 |
24 | 1 | 20 | 0 | 2017-06-30 16:25:26 |
26 | 1 | 30 | 3 | 2017-06-30 18:00:59 |
27 | 1 | 31 | 0 | 2017-06-30 18:01:17 |
28 | 1 | 18 | 2 | 2017-07-01 18:29:48 |
###SQL的には
以下のようにすると期待されるものが取得可能のようです。
sql
1SELECT * 2FROM survey_answers 3WHERE survey_answers.id = ( 4 SELECT sas.id 5 FROM survey_answers AS sas 6 WHERE survey_answers.examinee_id = sas.examinee_id 7 and survey_answers.survey_id = sas.survey_id 8 ORDER BY sas.starttime DESC 9 LIMIT 1 10)
もしくは、
sql
1SELECT * 2FROM survey_answers 3WHERE NOT exists ( 4 SELECT 1 5 FROM survey_answers AS sas 6 WHERE survey_answers.examinee_id = sas_b.examinee_id 7 and survey_answers.survey_id = sas.survey_id 8 and survey_answers.id < sas.id 9)
###補足情報(言語/FW/ツール等のバージョンなど)
PHP7.1/cakePHP3.4.8/mysql/
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/06 00:39