场景:student表中,我想按照班级、年龄、身高、分数的顺序优先查询先满足条件的结果。如给出一组数据: class_id=4, age=12, sex=150, score=100,则根据上面的优先顺序,先匹配班级,接着是年龄,身高和分数,因为班级中能匹配到张无忌这个学生,所以,最后返回张无忌这个学生的信息。
select s.*, 1 sort_num from student s where class_id = 4
union all
select s.*, 2 sort_num from student s where age = 12
union all
select s.*, 3 sort_num from student s where height = 150
union all
select s.*, 4 sort_num from student s where score = 100
order by sort_num
可以看到,符合这四个字段的数据都被查询到,因为我们自己加了sort_num
所以按照班级、年龄、身高、分数进行了排序,此时,我们只要加上limit 1取第一条就可以了。