用于加入两个查询的MySQL查询

问题描述:

我有一个mysql表,每行有一个学期的注册号,dob,学生姓名,性别,总分数。 我想在单个SQL查询中以总分数降序获得10个男孩和5个女孩的记录。用于加入两个查询的MySQL查询

我的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

试试这个代码:

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 

试试这个

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