原始的表 (用在例子中的):
- Orders 表:
Company | OrderNumber |
IBM | 3532 |
W3School | 2356 |
Apple | 4698 |
W3School | 6953 |
实例 1
以字母顺序显示公司名称:
SELECT Company, OrderNumber FROM Orders ORDER BY Company
- 结果:
Company | OrderNumber |
Apple | 4698 |
IBM | 3532 |
W3School | 6953 |
W3School | 2356 |
实例 2
以字母顺序显示公司名称(Company),并以数字顺序显示顺序号(OrderNumber):
SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber
- 结果:
Company | OrderNumber |
Apple | 4698 |
IBM | 3532 |
W3School | 2356 |
W3School | 6953 |
实例 3
以逆字母顺序显示公司名称:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
- 结果:
Company | OrderNumber |
W3School | 6953 |
W3School | 2356 |
IBM | 3532 |
Apple | 4698 |
实例 4
以逆字母顺序显示公司名称,并以数字顺序显示顺序号:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC
- 结果:
Company | OrderNumber |
W3School | 2356 |
W3School | 6953 |
IBM | 3532 |
Apple | 4698 |
注意:在以上的结果中有两个相等的公司名称 (W3School)。只有这一次,在第一列中有相同的值时,第二列是以升序排列的。如果第一列中有些值为 nulls 时,情况也是这样的。
INSERT INTO 语句
- INSERT INTO 语句用于向表格中插入新的行。
语法
INSERT INTO 表名称 VALUES (值1, 值2,....)
我们也可以指定所要插入数据的列:
INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
- 插入新的行
- "Persons" 表:
LastName | FirstName | Address | City |
Carter | Thomas | Changan Street | Beijing |
SQL 语句:
INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing')
- 结果:
LastName | FirstName | Address | City |
Carter | Thomas | Changan Street | Beijing |
Gates | Bill | Xuanwumen 10 | Beijing |
在指定的列中插入数据
- "Persons" 表:
LastName | FirstName | Address | City |
Carter | Thomas | Changan Street | Beijing |
Gates | Bill | Xuanwumen 10 | Beijing |
SQL 语句:
INSERT INTO Persons (LastName, Address) VALUES ('Wilson', 'Champs-Elysees')
- 结果:
LastName | FirstName | Address | City |
Carter | Thomas | Changan Street | Beijing |
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Champs-Elysees |
Update 语句
Update 语句用于修改表中的数据。
语法:
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
- Person:
LastName | FirstName | Address | City |
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Champs-Elysees |
更新某一行中的一个列
我们为 lastname 是 "Wilson" 的人添加 firstname:
UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
- 结果:
LastName | FirstName | Address | City |
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Fred | Champs-Elysees |
更新某一行中的若干列
我们会修改地址(address),并添加城市名称(city):
UPDATE Person SET Address = 'Zhongshan 23', City = 'Nanjing' WHERE LastName = 'Wilson'
- 结果:
LastName | FirstName | Address | City |
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Fred | Zhongshan 23 | Nanjing |
DELETE 语句
DELETE 语句用于删除表中的行。
语法
DELETE FROM 表名称 WHERE 列名称 = 值
- Person:
LastName | FirstName | Address | City |
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Fred | Zhongshan 23 | Nanjing |
删除某行
"Fred Wilson" 会被删除:
DELETE FROM Person WHERE LastName = 'Wilson'
- 结果:
LastName | FirstName | Address | City |
Gates | Bill | Xuanwumen 10 | Beijing |
删除所有行
可以在不删除表的情况下删除所有的行。这意味着表的结构、属性和索引都是完整的:
DELETE FROM table_name
或者:
DELETE * FROM table_name