联合查询 子查询

distinct 去除重复记录. 重复的记录,指的是字段值都相同的记录,而不是部分字段相同的记录

       例: select distinct days from teacher_class;

union 联合查询  将多跳select语句的结果合并到一起,称之为联合操作。

       例:(select t_name,days from teacher_class where c_name='php0115' order by days desc linit 1) union (select t_name,days from teacher_class where c_name='php0225' order by days desc limit1)

场景:获得数据的条件,出现逻辑冲突,或者很难在一个逻辑内表示,就可以拆分成多个逻辑分别实现,最后将结果合并到一起。

如果union的结果存在重复的记录,那么会消除重复,可以通过选项all达到目的。

排序:

子语句结果的排序:

1 将子语句包裹子括号内

2 子语句的order by 只有在order by 配合limit时才生效,原因是:union在做子语句时,会对没有limit子句的order by 优化。

子查询

 场景:查询代课天数最多的那个老师的信息

       例:select t_name,gender from teacher_class order by days limit 1.

 先获得最多的代课天数是多少天,在判断哪个老师的代课天数和最大值是一样的

 var1=select max(days) from teacher_class.

  select t_name,gender from teacher_class where days=var1;

也就是 select t_name,gender from teacher_class where days=(select max(days) from teacher_class);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章