1. 程式人生 > >資料庫中常用的sql語句

資料庫中常用的sql語句

SQL是目前使用最為廣泛的資料庫語言之一。這裡,我總結了在資料庫上,用SQL語言對資料排序、過濾和分組,以及表、檢視、聯結、子查詢、遊標、儲存過程和觸發器等內容。

1.檢索資料

SELECT prod_nameFROM Products;

#檢索單列

SELECT prod_id, prod_name, prod_priceFROMProducts;

#檢索多列

SELECT * FROM Products;

#檢索所有列

SELECT DISTINCTvend_id FROMProducts;

#檢索不同的值

SELECTprod_name FROM Products LIMIT

5;

#返回不超過5行資料

SELECTprod_name FROM Products LIMIT 5 OFFSET 5;

#返回從第5行起的5行資料。LIMIT指定返回的行數,LIMIT帶的OFFSET指定從哪兒開始。

/* SELECT prod_name, vend_id

FROMProducts; */

SELECTprod_name

FROMProducts;

#多行註釋

2.排序檢索資料

SELECTprod_name

FROMProducts

ORDER BYprod_name;

#排序資料

SELECT prod_id, prod_price, prod_name

FROMProducts

ORDER BY prod_price, prod_name;

#按多個列排序

SELECT prod_id, prod_price, prod_name

FROMProducts

ORDER BY 2, 3;

#按列位置排序,第三行表示先按prod_price, 再按prod_name進行排序

SELECT prod_id, prod_price, prod_name

FROMProducts

ORDER BY prod_priceDESC, prod_name;

#prod_price列以降序排序,而prod_name列(在每個價格內)仍然按標準的升序排序

3.過濾資料

SELECT prod_name, prod_price

FROMProducts

WHERE prod_price< 10;

#檢查單個值

SELECT prod_name, prod_price

FROMProducts

WHERE vend_id <> ‘DLL01’;

#不匹配檢查

SELECT prod_name, prod_price

FROMProducts

WHERE prod_priceBETWEEN 5 AND 10;

#範圍值檢查

SELECT cust_name

FROMCUSTOMERS

WHERE cust_emailIS NULL;

#空值檢查

4.高階資料過濾

SELECTprod_id, prod_price, prod_name

FROMProducts

WHERE vend_id = ‘DLL01’ANDprod_price <= 4;

#AND操作符

SELECTprod_name, prod_price

FROMProducts

WHEREvend_id=’DLL01’ OR vend_id=’BRS01’;

#OR操作符

SELECTprod_name, prod_price

FROMProducts

WHERE (vend_id = ’DLL01’ORvend_id=’BRS01’)

       ANDprod_price >= 10;

#求值順序 AND的優先順序高於OR

SELECTprod_name, prod_price

FROMProducts

WHERE vend_idIN (‘DLL01’,’BRS01’)

ORDER BY prod_name;

#IN操作符

SELECT prod_name

FROMProducts

WHERE NOTvend_id = ‘DLL01’

ORDER BY prod_name;

#NOT 操作符

SELECT prod_name

FROMProducts

WHEREvend_id <> ‘DLL01’

ORDER BY prod_name;

#NOT 操作符

5.萬用字元進行過濾

SELECT prod_id, prod_name

FROMProducts

WHERE prod_nameLIKE ‘Fish%’;

#%表示任何字元出現任意次數,找出所有以詞Fish起頭的產品

SELECT prod_id, prod_name

FROMProducts

WHERE prod_nameLIKE ‘%bean bag%’;

#‘%bean bag%’表示匹配任何位置上包含文字bean bag的值,不論它在之前或之後出現什麼字元

SELECT prod_name

FROMProducts

WHERE prod_nameLIKE ‘F%y’;

#找出以F起頭,以y結尾的所有產品

根據郵件地址的一部分來查詢電子郵件,例如WHERE email LIKE ‘b%@forta.com’

WHERE prod_nameLIKE ‘%’; #不會匹配產品名稱為NULL的行,其它均可

%代表搜尋模式中給定位置的0個、1個或多個字元

下劃線的用途與%一樣,但它只匹配單個字元,而不是多個字元

SELECT prod_id, prod_name

FROMProducts

WHERE prod_nameLIKE ‘__inchteddy bear’;

#搜尋模式要求匹配兩個萬用字元而不是一個

方括號([])萬用字元用來指定一個字符集,它必須匹配指定位置(萬用字元的位置)的一個字元

SELECT cust_contact

FROMCustomers

WHERE cust_contactLIKE ‘[JM]%’

ORDER BY cust_contact;

#[JM]匹配方括號中任意一個字元,它也只能匹配單個字元,任何多於一個字元的名字都不匹配。[JM]之後的%萬用字元匹配第一個字元之後的任意數目的字元,返回所需結果。

SELECT cust_contact

FROMCustomers

WHERE cust_contactLIKE ‘[^JM]%’

ORDER BY cust_contact;

#以J和M之外的任意字元起頭的任意聯絡人名

6.建立計算欄位

SELECT Concat(vend_name, ‘ (‘, vend_country, ‘)’)

FROMVendors

ORDER BY vend_name;

輸出

Bear Emporium(USA)

Bears R Us (USA)

Doll House Inc.(USA)

Fun and Games(England)

SELECT Concat(vend_name, ‘ (‘, vend_country, ‘)’)

        ASvend_title

FROMVendors

ORDER BY vend_name; #給拼接而成新欄位起了一個名稱

SELECT prod_id,

quantity,

item_price,

quantity*item_price AS expanded_price

FROMOrderItems

WHERE order_num = 20008;

#彙總物品的價格

7.使用函式處理資料

SELECT vend_name, UPPER(vend_name)AS vend_name_upcase

FROMVendors

ORDER BY vend_name;

#文字處理函式

SELECT cust_name, cust_contact

FROMCustomers

WHERE SOUNDEX(cust_contact) =SOUNDEX(‘MichaelGreen’);

# SOUNDEX()函式搜尋,匹配所有發音類似於Michael Green 的聯絡名

SELECT order_num

FROMOrders

WHERE YEAR(order_date) = 2012;

#從日期中提取年份

8.資料彙總

SELECT AVG(prod_price)ASavg_price

FROMProducts;

WHERE vend_id = ‘DLL01’;

SELECT COUNT(*)ASnum_cust

FROMCustomers;

#COUNT(*)對錶中行的數目進行計數,不管表列中包含的是空值(NULL)還是非空值

SELECT COUNT(cust_email)ASnum_cust

FROMCustomers;

#只對具有電子郵件地址的客戶計數

SELECT MAX(prod_price)ASmax_price

FROMProducts;

#返回Products表中最貴物品的價格

SELECT MIN(prod_price)ASmin_price

FROMProducts;

#返回Products表中最便宜物品的價格

SELECT SUM(quantity)ASitems_ordered

FROMOrderItems

WHERE order_num = 20005;

#SUM(quantity)返回訂單中所有物品數量之和,WHERE 子句保證只統計某個物品訂單中的物品

SELECT SUM(item_price*quantity)AS total_price

FROMOrderItems

WHERE order_num = 20005;

#SUM(item_price*quantity)返回訂單中所有物品價錢之和,WHERE子句保證只統計某個物品訂單中的物品

SELECT AVG(DISTINCTprod_price)AS avg_price

FROMProducts

WHERE vend_id = ‘DLL01’;

#使用DISTINCT引數,平均值只考慮各個不同的價格

SELECT COUNT(*) AS num_items,

        MIN(prod_price)AS price_min,

        MAX(prod_price)AS price_max,

        AVG(prod_price)AS price_avg

FROMProducts;

#組合聚集函式

9.分組資料

SELECT vend_id,COUNT(*) AS num_prods

FROMProducts

GROUP BY vend_id;

#建立分組

SELECT vend_id,COUNT(*) AS num_prods

FROMProducts

WHERE prod_price >= 4

GROUP BY vend_id

HAVING COUNT(*) >= 2;

#WHERE 子句過濾所有prod_price至少為4的行,然後按vend_id分組資料,HAVING子句過濾計數為2或2以上的分組。

SELECT order_num,COUNT(*) AS items

FROMOrderItems

GROUP BY order_num

HAVING COUNT(*) >= 3

ORDER BY items, order_num;

#按訂購物品的數目排序輸出

10.使用子查詢

SELECT cust_id

FROMOrders

WHERE order_numIN (SELECT order_num

                    FROM OrderItems

                    WHERE prod_id = ‘RGAN01’);

SELECT cust_name, cust_contact

FROMCustomers

WHERE cust_idIN (‘10000000004’, ‘10000000005’);

11.聯結表

SELECT vend_name, prod_name, prod_price

FROMVendors, Products

WHERE Vendors vend_id = Products.vend_id;

#建立聯結

SELECT vend_name, prod_name, prod_price

FROMVendorsINNER JOIN Products

ONVendors.vend_id = Products.vend_id;

#內聯結

SELECT prod_name, vend_name, prod_price, quantity

FROMOrderItems, Products, Vendors

WHERE Products.vend_id = Vendors.vend_id

ANDOrderItems.prod_id = Products.prod_id

ANDorder_num = 20007;

#聯結多個表

12.建立高階聯結

SELECT c1.cust_id, c1.cust_name, c1.cust_contact

FROMCustomersAS c1, Customers AS c2

WHERE c1.cust_name = c2.cust_name

ANDc2.cust_contact = ‘Jim Jones’;

#自聯結,此查詢中需要的兩個表實際上是相同的表

SELECT C. *, O.order_num, O.order_date,

        OI.prod_id, OI.quantity, OI.item_price

FROMCustomersAS C, Orders AS O, OrderItems AS OI

WHERE C.cust_id = O.cust_id

ANDOI.order_num = O.order_num

ANDprod_id = ‘RGAN01’;

#自然聯結排除多次出現,使每一列只返回一次

SELECT Customers.cust_id, Orders.order_num

FROMCustomersLEFT OUTER JOIN Orders

ONCustomers.cust_id = Orders.cust_id;

#從FROM子句左邊的表Customers表中選擇所有行

SELECT Customers.cust_id, Orders.order_num

FROMCustomersRIGHT OUTER JOIN Orders

ONOrders.cust_id =Customers.cust_id;

#從右邊的表中選擇所有行。

SELECT Customers.cust_id, Orders.order_num

FROMOrdersFULL OUTER JOIN Customers

ONOrders.cust_id = Customers.cust_id;

#檢索兩個表中的所有行並關聯那些可以關聯的行

13.組合查詢

SELECT cust_name, cust_contact, cust_email

FROMCustomers

WHERE cust_state IN (‘IL’, ‘IN’, ‘MI’)

UNION

SELECT cust_name, cust_contact, cust_email

FROMCustomers

WHERE cust_name = ‘Fun4ALL’

ORDER BY cust_name, cust_contact;

#SQL允許執行多個查詢,並將結果作為一個查詢結果集返回

14.插入資料

INSERT INTO Customers(cust_id,

                       Cust_name,

                       Cust_address,

                       Cust_city,

                       Cust_state,

                       Cust_zip,

                       Cust_country,

                       Cust_contact,

                       Cust_email)

VALUES(‘100000000006’,

         ‘Toy Land’,

         ‘123 Any Street’,

         ‘New York’,

         ‘NY’,

         ‘111111’,

         ‘USA’,

         NULL,

         NULL);

#插入完整的行

INSERT INTO Customers(cust_id,

                      Cust_contact,

                      Cust_email,

                      Cust_name,

                      Cust_address,

                      Cust_city,

                      Cust_state,

                      Cust_zip,

                      Cust_country)

SELECT cust_id,

        Cust_contact,

        Cust_email,

        Cust_name,

        Cust_address,

        Cust_city,

        Cust_state,

        Cust_zip,

        Cust_country

FROMCustNew;

#將另一個表中的顧客列合併到Customers表中。

SELECT *

INTOCustCopy

FROMCustomers;

#從一個表複製到另一個表中

15.更新和刪除資料

UPDATE Customers

SETcust_contact = ‘Sam Roberts’,

Cust_email = ‘[email protected]

WHERE cust_id = ‘100000000000006’;

#更新多個列

UPDATE Customers

SETcust_email = NULL

WHERE cust_id = ‘1000000005’;

#刪除某個列

DELETE FROM Customers

WHERE cust_id = ‘1000000006’;

#刪除資料

16. 建立和操縱表

CREATE TABLE OrderItems

(

Order_num        INTEGER         NOT NULL,

Order_item        INTEGER         NOT NULL,

Prod_id            CHAR(10)         NOT NULL,

Quantity          INTEGER          NOT NULL          DEFAULT 1,

Item_price         DECIMAL(8, 2)    NOT NULL

);

ALTER TABLE Vendors

ADDvend_phone CHAR(20);

#給表增加一個名為vend_phone的列,其資料型別為CHAR

ALTER TABLE Vendors

DROP COLUMN vend_phone;

#該表中的某列

DROP TABLE CustCopy;

#刪除表

17.高階SQL特性

主鍵:表中一列(或多個列)的值唯一標識表中的每一行。主鍵是一種特殊的約束,用來保證一列或一組列的值唯一標識表中的每一行。這方便直接或互動地處理表中的行。沒有主鍵,要安全地UPDATE 或DELETE特定行而不影響其他行會非常困難。

①任意兩行的主鍵值都不相同;

      ②每行都具有一個主鍵值(即列中不允許NULL值)

      ③包含主鍵值的列從不修改或更新。

      ④主鍵值不能重用

CREATE TABLE Vendors

(

Vend_id           CHAR(10)          NOT NULL PRIMARYKEY,

Vend_name         CHAR(50)          NOT NULL,

Vend_address       CHAR(50)          NULL,

Vend_city          CHAR(5)           NULL,

Vend_state         CHAR(10)          NULL,

Vend_zip           CHAR(10)          NULL,

Vend_country        CHAR(50)          NULL

);

ALTER TABLE Vendors

ADD CONSTRAINT PRIMARY KEY (vend_id);

#給表vend_id 列定義新增關鍵字PRIMARYKEY, 使其成為主鍵

五、演算法