如何在mysql查询结果中包含特定的条目

时间:2018-04-16 09:33:11

标签: mysql ruby-on-rails

这是我的MySQL查询。

SELECT * FROM myschool.term_reports
where class = 4 and term = 2 and year = 2018 and studentid = '19' or subject_id = 31
order by score
limit 6;

现在结果不包括subject_id 31,因为得分不在最佳6个科目中。但是,subject_id 31是一个关键主题,它应该包含在最好的6.如何将其添加到结果中?

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个..如果我没有测试过任何问题请告诉我

SELECT * FROM myschool.term_reports
where class = 4 and term = 2 and year = 2018 and studentid = '19' and subjectid=31
union
SELECT * FROM myschool.term_reports
where class = 4 and term = 2 and year = 2018 and studentid = '19' 
order by score
limit 5;

答案 1 :(得分:0)

试试这个..如果我没有测试过任何问题请告诉我

SELECT * FROM myschool.term_reports
WHERE class = 4
    AND term = 2
    AND year = 2018
    AND studentid = '19'
    OR subject_id = 31
ORDER BY CASE WHEN subject_id = 31 THEN 0 ELSE score END limit 6;