我從你的問題是,你想要得到「正確的」,「項」,「百分比」等。 bcc_fs_exam_result
中具有最後一個或第一個日期的行的列。
如果這是正確的,那麼您可以通過首先找到每個id_user
的最小或最大日期,然後將其加入考試結果表中,過濾bcc_fs_exam_result
。
SELECT
r.correct,
r.items,
r.percentage,
r.date_taken,
u.username,
u.FN,
u.user_course_type,
IFNULL(u.user_major_type,'N/A') as user_major_type,
u.level_name,
u.section_name
FROM bcc_fs_exam_result r
INNER JOIN (
SELECT u.id_user,
u.username,
CONCAT(u.lastname,', ',u.firstname) as FN,
c.user_course_type,
m.user_major_type,
l.level_name,
s.section_name
FROM bcc_fs_user u
LEFT JOIN bcc_fs_user_course c on c.id_user_course = u.id_user_course
LEFT JOIN bcc_fs_user_major m on m.id_user_major = u.id_user_major
LEFT JOIN bcc_fs_group_level l ON l.id_level = u.id_level
LEFT JOIN bcc_fs_group_section s ON s.id_section = u.id_section
) u ON r.id_user = u.id_user
INNER JOIN (
SELECT
id_user, max(r.date_taken) as last_date_taken
FROM bcc_fs_exam_result
GROUP BY id_user
) as lastdate ON lastDate.id_user = r.id_user and r.date_taken = lastdate.last_date_taken
這可以更簡單地寫爲:
SELECT
r.correct,
r.items,
r.percentage,
r.date_taken,
u.username,
CONCAT(u.lastname,', ',u.firstname) as FN,
c.user_course_type,
IFNULL(m.user_major_type,'N/A') as user_major_type,
l.level_name,
s.section_name
FROM bcc_fs_exam_result r
INNER JOIN (
SELECT
id_user, max(r.date_taken) as last_date_taken
FROM bcc_fs_exam_result
GROUP BY id_user
) as lastdate ON lastDate.id_user = r.id_user and r.date_taken = lastdate.last_date_taken
INNER JOIN bcc_fs_user u on r.id_user = u.id_user
LEFT JOIN bcc_fs_user_course c on c.id_user_course = u.id_user_course
LEFT JOIN bcc_fs_user_major m on m.id_user_major = u.id_user_major
LEFT JOIN bcc_fs_group_level l ON l.id_level = u.id_level
LEFT JOIN bcc_fs_group_section s ON s.id_section = u.id_section
你認爲id_user
+ date_taken
是bcc_fs_exam_result
代理鍵,你或許應該有約束,如果在所有可能強制執行。否則,從您的樣本數據看,唯一ID列id_result
的順序跟在date_taken
之後,所以您可能最好使用Max(id_result)
而不是Max(date_taken)
。這將避免返回重複的行爲一個id_user
其中兩行bcc_fs_exam_result
具有相同的taken_date
和`id_user。
日期改變,但(正確的,項目和百分比)根本沒有改變我所缺的是什麼 –
基本上它是相連的,畢竟他們在同一張表中,所以它應該與其他字段一致,只要我使用日期字段(正確,項目和百分比)保持不變 –