資料庫學習筆記四 複雜語句(3)

2021-10-10 17:21:40 字數 2172 閱讀 2650

union 操作符用於合併兩個或多個 select 語句的結果集。

union 內部的每個 select 語句必須擁有相同數量的列。列也必須擁有相似的資料型別。同時,每個 select 語句中的列的順序必須相同。 語法

select column_name(s) from table1

union

select column_name(s) from table2;

預設地,union 操作符選取不同的值。如果允許重複的值,使用 union all

sql union all 語法

select column_name(s) from table1

union all

select column_name(s) from table2;

union 結果集中的列名總是等於 union 中第乙個 select 語句中的列名

帶有 where 的 sql union all例項:

select country, name from websites

where country=

'cn'

union all

where country=

'cn'

order by country;

使用union命令時需要注意,只能在最後使用乙個order by命令,是將兩個查詢結果合在一起之後,再進行排序。

絕對不能寫兩個order by命令。

另外,在使用order by排序時,注意兩個結果的別名保持一致,使用別名排序很方便。當然也可以使用列數。

select country,name from websites where country =

'cn' union all

'cn' order by name;

--通過where條件查詢的結果,連線連個表的結果集,並根據名字排序。

order by 除了可以對指定的字段進行排序,還可以使用函式進行排序:

order by abs(a);

order by 只能當前 sql 查詢結果進行排序,如要對 union all 出來的結果進行排序,需要先做集合。

select aa.* from 

(select country,name from websites where country =

'cn'

'cn'

) aa

order by aa.name;

select into 語句從乙個表複製資料,然後把資料插入到另乙個新錶中。

注意:mysql 資料庫不支援 select … into 語句,但支援 insert into … select 。

也可以使用以下語句來拷貝表結構及資料:

create table 新錶

asselect * from 舊表

sql select into 語法:

可以複製所有的列插入到新錶中:

select *

into newtable [in externaldb]

from table1;

或者只複製希望的列插入到新錶中:

select column_name(s)

into newtable [in externaldb]

from table1;

例:複製多個表中的資料插入到新錶中:

select websites.name, access_log.count, access_log.date

into websitesbackup2016

from websites

left join access_log

on websites.id=access_log.site_id;

select *

into newtable

from table1

where 1=0;

「?的乙個上午」

資料庫學習筆記二 複雜語句(1)

這幾個語句都是用於篩選出特定條數的資料 一般大型資料庫常用 變相返回後 n 行 前5行 select top 5 from table 後5行 select top 5 from table order by id desc desc 表示降序排列 asc 表示公升序like 操作符用於在 wher...

資料庫學習筆記(SQL語句)

根據已有的表或查詢結果來建立表 create table like會根據原有表建立乙個新錶。該語句會完整的複製原有表的結構以建立乙個新的空表。如果想插入資料,還需要另外的插入語句 如insert into select 但它不能只選原表的某幾列或其他表中的列。create table select可...

MySQL資料庫學習筆記(3)

mysql中的函式包括 字元函式 數值運算子與函式 比較運算子與函式 日期時間函式 資訊函式 聚合函式 加密函式等。1 字元函式 比如說,需要將姓和名一起輸出時 前導空格是指第乙個字元之前的空格,後續空格是指最後乙個字元之後的空格。注意 mysql中的字串編號從1開始。select substrin...