返回结果
Company
OrderNumber
ABC Shop
5678
Sega
3412
W3Schools
6798
W3Schools
2312
按照Company字段的降序方式返回结果集:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
返回结果:
Company
OrderNumber
W3Schools
6798
W3Schools
2312
Sega
3412
ABC Shop
5678
Group by
用途:
对结果集进行分组,常与汇总函数一起使用。
语法:
SELECT column,SUM(column) FROM table GROUP BY column
例:
“Sales”表中的原始数据:
Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
按照Company字段进行分组,求出每个Company的Amout的合计:
SELECT Company,SUM(Amount) FROM Sales GROUP BY Company
返回结果:
Company
SUM(Amount)
W3Schools
12600
IBM
4500
Having
用途:
指定群组或汇总的搜寻条件。
语法:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value
解释:
HAVING 通常与 GROUP BY 子句同时使用。不使用 GROUP BY 时,HAVING 则与 WHERE 子句功能相似。
例:
“Sales”表中的原始数据:
Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
按照Company字段进行分组,求出每个Company的Amout的合计在10000以上的数据:
SELECT Company,SUM(Amount) FROM Sales GROUP BY Company HAVING SUM(Amount)>10000
返回结果:
Company
SUM(Amount)
W3Schools
12600
Join
用途:
当你要从两个或者以上的表中选取结果集时,你就会用到JOIN。
例:
“Employees”表中的数据如下,(其中ID为主键)
ID
Name
01
Hansen, Ola
02
Svendson, Tove
03
Svendson, Stephen
04
Pettersen, Kari
“Orders”表中的数据如下:
ID
Product
01
Printer
03
Table
03
Chair
用Employees的ID和Orders的ID相关联选取数据:
SELECT Employees.Name, Orders.Product FROM Employees, Orders WHERE Employees.ID = Orders.ID
返回结果:
Name
Product
Hansen, Ola
Printer
Svendson, Stephen
Table
Svendson, Stephen
Chair
或者你也可以用JOIN关键字来完成上面的操作:
SELECT Employees.Name, Orders.Product FROM Employees INNER JOIN Orders ON Employees.ID = Orders.ID
INNER JOIN的语法:
SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
解释:
?????? INNER JOIN返回的结果集是两个表中所有相匹配的数据。
LEFT JOIN的语法:
SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
用”Employees”表去左外联结”Orders”表去找出相关数据:
SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders