聯表查詢 union的使用

2021-08-04 16:02:17 字數 1472 閱讀 7976

直接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所以都可以用)

聯表查詢的更新

背景 之前寫過一篇關於資料庫聯表查詢的部落格 再看資料庫 6 連線 主要講了連線的型別,以及如何使用連線進行多表查詢。本篇部落格就是在這基礎上延伸而來的。首先,我們先來看乙個聯表查詢的例子。use testunion 員工集合 create table staffunion id int prima...

zf聯表查詢

zf支援聯表查詢,並且會經常遇到聯表查詢,具體 寫法如下 select this select select from this name,array id name select distinct select joinleft jobname,jobname.enterprise id this...

sql聯表查詢

比如 all list 這個表,是包含所有資料的,我們要把整個資料的某些字段查詢出來顯示在列表上 select from all list select 現在我要檢視一條資料,需要根據表 user list 的乙個字段內容,去檢視另外乙個表 info list 的內容 select dept nam...