2017-04-22 35 views
0

enter image description here如何從MySQL表

得到最後和Secondlast記錄從上面的圖片,我有ň的記錄與號CAT_IDsub_cat_id但在圖像只有兩個在那裏。

,所以我希望得到最後secondlastscore_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 logics..This我曾嘗試..

例子: 可以說,一個用戶的電子郵件是[email protected]採取相同的測試2時間和測試與一個類別和子類別相關聯。 所以用戶會參加任何次數的測試...

從那條記錄我想得到最後兩個記錄的百分比。

+0

你的子查詢有什麼問題?你想要什麼結果?我看不到圈出來的行是最新的還是最新的。 –

+0

它不工作,有時它說內部查詢得到多個值..現在latetsScore來了,但最後得分作爲'空' –

+0

讓我解釋清楚有問題給一分鐘。 –

回答

0
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 
1

如果我理解正確;您想要選擇特定學生所進行的特定類型考試的兩個最新結果。

您不正確使用LIMIT子句。這是正確的語法: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; 

如果一個學生可以參加IELTS考試在一天內多次(如圖像建議)應該比你還爲了通過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; 
1

一個解決這個問題的方法是使用分區通過
Step1:我已經按照分區的降序排列了不同的cat_id和sub_cat_id的數據。
第二步:我已經使用等級-1這是最新的分數,並與秩2合併,它是倒數第二個得分

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; 

讓我知道的任何查詢的情況。