一、數據定義 1、創建新資料庫:CREATE DATABASE database_name2、創建新表:CREATE TABLE table_name (column_name datatype,column_name datatype,...)3、修改數據表: 添加列:ALTER TABLE ta ...
一、數據定義
1、創建新資料庫:CREATE DATABASE database_name
2、創建新表:CREATE TABLE table_name (column_name datatype,column_name datatype,...)
3、修改數據表:
添加列:ALTER TABLE table_name ADD column_name datatype
刪除列:ALTER TABLE table_name DROP COLUMN column_name
修改列:ALTER TABLE table_name ALTER COLUMN column_name datatype
4、刪除表:DROP TABLE table_name
二、數據操作
選取數據:SELECT 列名稱 FROM 表名稱
SELECT * FROM 表名稱
過濾重覆:SELECT DISTINCT 列名稱 FROM 表名稱
指定條件:SELECT 列名稱 FROM 表名稱 WHERE 列 運算符 值
多項條件:SELECT 列名稱 FROM 表名稱 WHERE 列 運算符 值 AND(OR) 列 運算符 值
排列順序:SELECT 列名稱 FROM 表名稱 ORDER BY 列1,列2 DESC(列1升序然後列2倒敘)
插入數據:INSERT INTO 表名稱 VALUES (值1, 值2,...)
INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
更新數據:UPDATE 表名稱 SET 列名稱 = 新值 WHERE 列名稱 = 某值
刪除數據:DELETE FROM 表名稱 WHERE 列名稱 = 值
三、常用SQL語句範例
選取:SELECT LastName,FirstName FROM Persons
去重:SELECT DISTINCT Company FROM Orders
條件:SELECT * FROM Persons WHERE City='Beijing'
AND與:SELECT * FROM Persons WHERE FirstName='Thomas' AND LastName='Carter'
OR或:SELECT * FROM Persons WHERE firstname='Thomas' OR lastname='Carter'
升序:SELECT Company, OrderNumber FROM Orders ORDER BY Company
降序:SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
插入1:INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing')
插入2:INSERT INTO Persons (LastName, Address) VALUES ('Wilson', 'Champs-Elysees')
更新:UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
刪除:DELETE FROM Person WHERE LastName = 'Wilson'
限制條數:SELECT * FROM Persons LIMIT 5
字元檢索:SELECT * FROM Persons WHERE City LIKE '%BJ%'
通配符:%:替代一個或多個字元
_:僅替代一個字元;
[ABC]:ABC三者之一;
[^ABC]:除ABC以外
多選條件:SELECT * FROM Persons WHERE LastName IN ('Adams','Carter')
兩者之間:SELECT * FROM Persons WHERE LastName BETWEEN 'Adams' AND 'Carter'
指定別名:SELECT po.OrderID, p.* FROM Persons AS p, Product AS po WHERE p.LastName='Adams' AND p.FirstName='John'
聯合查詢:SELECT Persons.*, Orders.OrderNo FROM Persons, Orders WHERE Persons.Id_P = Orders.Id_P
JOIN聯合:SELECT Persons.*, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.Id_P = Orders.Id_P
合併結果:SELECT E_Name FROM Employees_China UNION SELECT E_Name FROM Employees_USA