+----+-------------------------+--------+------------+-------+--------+--------------+------------+
| id | user_email | cat_id | sub_cat_id | score | out_of | score_in_per | date |
+----+-------------------------+--------+------------+-------+--------+--------------+------------+
| 13 | [email protected] | 9 | 11 | 40 | 40 | 100 | 22-04-2017 |
+----+-------------------------+--------+------------+-------+--------+--------------+------------+
| 14 | [email protected] | 9 | 11 | 37 | 40 | 92.5 | 22-04-2017 |
+----+-------------------------+--------+------------+-------+--------+--------------+------------+
| 26 | [email protected] | 9 | 11 | 36 | 40 | 88 | 23-04-2017 |
+----+-------------------------+--------+------------+-------+--------+--------------+------------+
| 27 | [email protected] | 9 | 11 | 35 | 40 | 80 | 23-04-2017 |
+----+-------------------------+--------+------------+-------+--------+--------------+------------+
從上表我想這樣的記錄誰能幫助我/如何獲取最後和最新的記錄。以及如何在子查詢中使用它。
+-----------+-----------------+---------------+-------------------------+--------+------------+-------+--------+--------------+------+
| lastScore | secondLastScore | maxPortaScore | user_email | cat_id | sub_cat_id | score | out_of | score_in_per | date |
+-----------+-----------------+---------------+-------------------------+--------+------------+-------+--------+--------------+------+
| 80 | 88 | 100 | [email protected] | 9 | 11 | - | - | - | - |
+-----------+-----------------+---------------+-------------------------+--------+------------+-------+--------+--------------+------+
這是我的查詢:
SELECT
scor.id,
(SELECT score_in_per
FROM tbl_student_skill_score
WHERE cat_id = scor.cat_id and sub_cat_id = scor.sub_cat_id and scor.user_email='[email protected]'
ORDER BY scor.date DESC,scor.id DESC LIMIT 1)
as lastScore,
(SELECT score_in_per
FROM tbl_student_skill_score
WHERE cat_id=scor.cat_id and sub_cat_id=scor.sub_cat_id and scor.user_email='[email protected]'
ORDER BY scor.date DESC,scor.id DESC LIMIT 1,1)
as secondLastScore,
(SELECT max(cast(score_in_per as decimal(5,2)))
FROM tbl_student_skill_score
WHERE cat_id = scor.cat_id and sub_cat_id=scor.sub_cat_id)
as maxPortaScore,
scor.user_email,scor.cat_id,
scor.sub_cat_id,scor.score, scor.out_of,
scor.score_in_per,scor.date
FROM
tbl_student_skill_score scor
LEFT JOIN
tbl_skilltest_subcategory subc
ON
scor .sub_cat_id = subc.scat_id
LEFT JOIN
tbl_skilltest_category catg
ON subc.cat_id = catg.id
where
scor.user_email = '[email protected]'
GROUP BY
sub_cat_id
ORDER by
scor.id DESC,scor.date DESC
形成上述查詢lastScore和secondLastScore不工作
lastScore意味着我的情況從第一張表中最後存儲的記錄是id
:27記錄。所以結果應該是
同樣
secondLastScore意味着在我的情況下,從第一個表是id
的倒數第二個存儲的記錄:26的紀錄。所以結果應該是
maxPortaScore意味着橫跨表該特定類別的最大得分它不涉及在我的情況下,特定的學生是 我已經使用相同的用戶爲但實際上它可以是任何用戶評分。 [這工作是絕對精細]
如果用戶(電子郵件)只有一條記錄會怎麼樣?那麼什麼是'secondLastScore'值? –
'secondLastScore'將會是空白的......很好的問題btw @OtoShavadze –
學生可能只有一個'cat_id'和'sub_cat_id'? –