联表查询+union的使用

来源:互联网 发布:佛山新城网络联系方式 编辑:程序博客网 时间:2024/06/06 03:04

今天写了个难度系数为2的sql,感觉自己牛逼坏了(因为以前只会写难度1的哈哈)

直接show sql:

mysql> select * from std;
+----+-----+-------+
| id | sid | class |
+----+-----+-------+
|  1 |  11 |     1 |
|  2 |  21 |     1 |
|  3 |  13 |     2 |
|  4 |  14 |     3 |
|  5 |  51 |     2 |
|  6 |  16 |     2 |
|  7 |  17 |     1 |
+----+-----+-------+

mysql> select * from stdn;
+----+-----+------+
| id | sid | name |
+----+-----+------+
|  1 | 222 | 11   |
|  2 | 111 | 22   |
|  3 | 111 | 33   |
|  4 | 222 | 44   |
|  5 | 222 | 55   |
|  6 | 333 | 66   |
|  7 | 444 | 77   |
|  8 | 222 | 88   |
+----+-----+------+

一个学生班级表std,一个学生姓名表stdn

目标是查看学生姓名,要求把class=1的单独放到最上面,其他班的放后面。且各自按照std.sid升序。

select * from

(select std.id,std.sid,stdn.name,std.class from std left join stdn on std.id = stdn.id where std.class=1 order by std.sid) as a 

union all 

select * from

(select std.id,std.sid,stdn.name,std.class from std left join stdn on std.id = stdn.id where std.class!=1 order by std.sid) as b;

这是我查了不少资料搞出来的,联查加union的使用,需要注意的是union前面不能有order by,想想也是逻辑不通,如果后面也有order by

那不就是前面白写了。所以要想使用order by+union就得把有order by的语句封装成一个对象,再用select * from(......)as a union......。

(当然只在有union的语句的最后写个order by是ok的,就是两个查询结果放一起之后再排序的意思)

(顺便说下union 和union all的区别,前者去重且排序、后者不去重不排序,这里主要区分class是否为1所以都可以用)