SQL入門基礎

ice_moss發表於2022-05-18

建立表

CREATE TABLE Persons
(
    Id_p int,
    Last_name varchar(255),
    Frisr_name varchar(255),
    Address varchar(255),
    City varchar(255)
);

INSERT – 插入資料

向表中插入行資料 :

INSERT INTO Persons VALUES (1, 'KUANG', 'YANG', 'WUXIUniversity', 'WuXi');

在指定的列中插入資料:

INSERT INTO Persons (Address, City) VALUES ('北京路32號', '上海市');

SELECT – 查詢資料

查詢表中資料, *表示查詢所有欄位:

SELECT * FROM Persons;

按照條件查詢資料 :

SELECT City FROM Persons;
SELECT Last_name, Frisr_name FROM Persons;

DISTINCT篩選欄位中唯一值:

SELECT City from Persons;
SELECT DISTINCT City FROM Persons;

後續內容需要:

INSERT INTO Persons VALUES(2, '小米', '馮', '1棟333號', '北京');
INSERT INTO Persons VALUES(2, '小李', '李', '4棟01號', '上海');
INSERT INTO Persons VALUES(2, '小成', '張', '33棟33號', '北京');
INSERT INTO Persons VALUES(2, '小同', '康', '43棟9號', '深圳'); 

根據條件查詢 :

SELECT * FROM Persons WHERE City='北京';
SELECT * FROM Persons WHERE Id_p>1;
SELECT * FROM Persons WHERE Id_p=1;

and 和 or邏輯條件查詢:

SELECT * FROM Persons WHERE City='北京'AND Id_p>1;
SELECT * FROM Persons WHERE City='上海'OR Id_p>10;

SELECT * FROM Persons WHERE (City='北京' AND Id_p>1) OR Last_name='小成';

ORDER BY排序 預設為升序,可以使用 DESC 關鍵字降序:

SELECT * FROM Persons ORDER BY City;
SELECT * FROM Persons order BY Last_name;
SELECT * FROM Persons ORDER BY City DESC;

UPDATE – 更新資料

更新 欄位City=’上海市’,的其他指定欄位例如:Id_p=1, Last_name=’小曠’, Frisr_name=’楊’:

UPDATE Persons SET Id_p=1, Last_name='小曠', Frisr_name='楊' WHERE City='上海市';

DELETE – 刪除資料

刪除欄位City=’WuXi’的行:

DELETE FROM Persons WHERE City='WuXi';

不刪除表,刪除所有行:

DELETE FROM Persons;
SELECT * FROM Persons;

DROP TABLE – 刪除表:

DROP TABLE Persons;```

本作品採用《CC 協議》,轉載必須註明作者和本文連結