2012-07-31 102 views
1

我有一個mysql表,每行有一個學期的註冊號,dob,學生姓名,性別,總分數。 我想在單個SQL查詢中以總分數降序獲得10個男孩和5個女孩的記錄。用於加入兩個查詢的MySQL查詢

回答

1

我的MySQL的方言是生鏽的,但這應該做的伎倆

(SELECT * FROM Students WHERE sex = 'Male' ORDER BY TotalMarks DESC LIMIT 10) 
UNION ALL 
(SELECT * FROM Students WHERE sex = 'Female' ORDER BY TotalMarks DESC LIMIT 5) 

這是一個單一的查詢,請注意。

+0

MYSQL回報#1221 - UNION的錯誤用法和ORDER BY。 \ n但是(選擇* FROM學生WHERE性別='男性'ORDER BY TotalMarks DESC LIMIT 10) UNION ALL (SELECT * FROM Students WHERE性別='女性'ORDER BY TotalMarks DESC LIMIT 5)作品。 \ n非常感謝 – Ajay 2012-07-31 14:03:07

+0

我會忘記括號,修正代碼。當然,不客氣 – Alex 2012-08-01 06:54:31

0

試試這個代碼:

select 
    a.studentID, 
    a.studentName, 
    a.dob, 
    a.totalMark 
from 
(
    select 
     studentID, 
     studentName, 
     dob, 
     totalMark 
    from 
     students 
    where 
     sex='M' 
    order by 
     studentMark desc 
    limit 10 
    union all 
    select 
     studentID, 
     studentName, 
     dob, 
     totalMark 
    from 
     students 
    where 
     sex='F' 
    order by 
     totalMark desc 
    limit 5 
) 
order by 
    totalMark desc 
0

試試這個

select * from 
    (select reg_number, dob, student_name, sex, total_marks where sex='male' 
    order by total_marks desc limit 10 
    union 
    select reg_number, dob, student_name, sex, total_marks where sex='female' 
    order by total_marks desc limit 5) a order by total_marks desc