order by
asc升序 ascending desc降序 descending多字段排序:先按照第一个字段排序,如果不能区分,按照第二个字段排序。排序是对检索出来的数据进行的排序,所以order by必须放在where的后面。
select * from t1 order by col1,col2 desc
limit
分页排序时用此命令就非常方便啦。limit语法: limit offset,row count 偏移位置,限制的行数。默认情况下offset为0,所以从最上面开始取N条。如果N大于数据库内数据,则全部取出,不报任何提示。
限制在顺序上应该最后,比order by还要后。
select * from t1 order by col1 limit 1,3; //从第二行开始取3个。
distinct
distinct需要放在指定字段的前面。像asc升序一样,默认的all一般不会被用到,但是可以写。select all col1 from t1;
select distinct * from t1; //所有的字段都相同才是重复
select distinct col1, col2 from t1; //col1和col2两个记录同时相同才认为是重复
select distinct col1 from t1;
union-纵向结合(join横向结合)
将两个搜索结果结合成一个结果,比如先显示第一列,再显示第二列,相当于把两列合成一列,要求两个子句检索的列数必须相同,否则无法结合。虽然当前mysql中两个子句查询的列类型不同不会报错(内部进行了类型转换),但是不建议这样做。最好检查相同类型的列。select col1 from t1 union select col2 from t1;
select col1_char from t1 union select col2_int from t1; //col1_char 和 col2_int类型不同,不推荐。
为了显示清晰,可以在不同的语句加上括号。
(select student_id from student)
union
(select student_name from student);
**union陷阱-消除重复**
如果union查询中有重复的记录,会被消除。为了防止此问题发生需要显示的指定all
(select student_id from student)union all
(select student_name from student);
**union陷阱-排序**
用union连接两个查询语句,每个句子成为子语句。union对子句的排序进行了特殊处理,如果子句没有limit语句,则不会进行排序。如果想在子语句执行排序,需要同时满足两个条件1)括号括起来,2)有limit语句(如果想全部显示则给以个大于总数的值即可)。
(select student_name from t1 order by id desc limit 10)
union all
(select student_name from t2 order by id asc limit 20);
如果是对union之后的结果集排序则没有此问题。
(select student_name from t1)
union all
(select student_name from t2) order by id desc; //排序放在括号外边,对union后的结果进行排序。
**union陷阱-列名**
两个子句如果列名不同时,检索出来的结果会以第一个子句的列名命名。select col1 from t1 union select col2 from t1;
+------------+
| col1 |
+------------+
| 1 |
| 2 |
| 3 |
| 4 |
《完》