簡體   English   中英

如何從mysql表中獲取Last和Secondlast記錄

[英]How to get Last and Secondlast Record from mysql table

在此處輸入圖片說明

從上面的圖像中,我有n條帶cat_idsub_cat_id的記錄,但是在圖像中只有兩條。

所以我想獲取最后一個倒數 第二個 score_in_per值,分別命名為lastScorelatetsScore ..

我該如何找回..?

SELECT
(SELECT score_in_per FROM tbl_student_skill_score ORDER BY date DESC LIMIT 2,0)  as lastScore,
(SELECT score_in_per FROM tbl_student_skill_score ORDER BY date DESC LIMIT 1)  as latetsScore

我是這個復雜的mysql邏輯的新手。

例如:可以說,一個用戶的電子郵件是inststudent@yopmail.com采取相同的測試2次,測試鏈接了一個類別和子類別。 因此用戶可以多次進行測試...

從該記錄,我想獲得最后兩個記錄的百分比。

如果我正確理解你的話; 您想選擇特定學生參加的特定類型考試的兩個最新結果。

您沒有正確使用LIMIT子句。 這是正確的語法: LIMIT {[offset,] row_count | row_count OFFSET offset} LIMIT {[offset,] row_count | row_count OFFSET offset} 另外,您完全省略了where子句。

因此查詢應為:

SELECT
(SELECT score_in_per FROM tbl_student_skill_score
  WHERE user_email = "email of the user you are interested in"
    AND cat_id = categoryOfTestOfInterest
    AND sub_cat_id = subcategoryOfTestOfInterest
  ORDER BY date DESC LIMIT 1, 1
)AS lastScore,
(SELECT score_in_per FROM tbl_student_skill_score
  WHERE user_email = "email of the user you are interested in"
    AND cat_id = categoryOfTestOfInterest
    AND sub_cat_id = subcategoryOfTestOfInterest
  ORDER BY date DESC LIMIT 1
)AS latetsScore;

如果一個學生一天可以參加多次考試(如您的圖像所示),則您還應該按id排序(假設對於新的結果,該id總是更大)或更好,而僅按id排序:

SELECT
(SELECT score_in_per FROM tbl_student_skill_score
  WHERE user_email = "email of the user you are interested in"
    AND cat_id = categoryOfTestOfInterest
    AND sub_cat_id = subcategoryOfTestOfInterest
  ORDER BY id DESC LIMIT 1, 1
)AS lastScore,
(SELECT score_in_per FROM tbl_student_skill_score
  WHERE user_email = "email of the user you are interested in"
    AND cat_id = categoryOfTestOfInterest
    AND sub_cat_id = subcategoryOfTestOfInterest
  ORDER BY id DESC LIMIT 1
)AS latetsScore;

解決此問題的方法之一是使用Partition By
步驟1:我已經按日期的降序對不同的cat_id和sub_cat_id的數據進行了划分。
步驟2:我使用了最新得分的rank1,並將其與倒數第二的rank2合並

with chck as
(select
   cat_id,sub_cat_id,score_in_per,date1,
   row_number() over(partition by cat_id,sub_cat_id order by 
   cat_id,sub_cat_id,date1 desc) as row_num
from tbl)

    select a.*,b.second_last_score from
    (select cat_id,sub_cat_id,score_in_per,date1,row_num as last_score from chck where row_num=1) a
    left join
    (select cat_id,sub_cat_id,score_in_per,date1,row_num as second_last_score from chck where row_num=2) b
    on a.cat_id = b.cat_id and a.sub_cat_id = b.sub_cat_id;  

如有任何查詢,請通知我。

SELECT  
(   SELECT score_in_per     FROM   tbl_student_skill_score WHERE cat_id=1 and sub_cat_id=5 ORDER BY date,id DESC LIMIT 1 ) AS latestScore,
(   SELECT score_in_per     FROM   tbl_student_skill_score WHERE cat_id=1 and sub_cat_id=5 ORDER BY date,id DESC LIMIT 1,1  ) AS lastScore

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM