天天看點

聯表查詢+union的使用

今天寫了個難度系數為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是以都可以用)