SQL 系列教程(二)

发布时间:2024年01月24日

目录

SQL?DELETE?语句

DELETE 语句

演示数据库

DELETE 实例

删除所有行

SQL?TOP, LIMIT, ROWNUM?子句

TOP 子句

演示数据库

SQL TOP、LIMIT 和 ROWNUM 示例

SQL TOP PERCENT 实例

添加WHERE子句

SQL?MIN() 和 MAX()?函数

MIN() 和 MAX() 函数

演示数据库

MIN() 实例

MAX() 实例

SQL?COUNT(), AVG() 和 SUM()?函数

COUNT(), AVG() 和 SUM() 函数

演示数据库

COUNT() 实例

AVG() 实例

演示数据库

SUM() 实例

SQL?LIKE?操作符

SQL LIKE 操作符

演示数据库

LIKE 操作符实例

SQL?通配符

SQL 通配符

演示数据库

使用 % 通配符

使用 _ 通配符

使用 [charlist] 通配符

使用 [!charlist] 通配符

SQL?IN?操作符

SQL IN 操作符

演示数据库

IN 操作符实例

SQL?BETWEEN?操作符

SQL BETWEEN 操作符

演示数据库

BETWEEN 实例

NOT BETWEEN 实例

带有 IN 的 BETWEEN 操作符实例

带有文本值的 BETWEEN 操作符实例

带有文本值的 NOT BETWEEN 操作符实例

示例表

带有日期值的 BETWEEN 操作符实例

SQL?别名

SQL 别名

演示数据库

Alias 实例: 使用一个列名别名

Alias 实例: 使用表名称别名

SQL?联接

SQL JOIN

不同类型的 SQL JOIN


SQL?DELETE?语句

DELETE 语句

DELETE 语句用于删除表中的记录。

【DELETE 语法】

DELETE FROM table_name WHERE condition;

注:?请注意 SQL DELETE 语句中的 WHERE 子句!WHERE 子句规定哪条记录或者哪些记录需要删除。如果您省略了 WHERE 子句,所有的记录都将被删除!

演示数据库

以下是从示例数据库的 "客户(Customers)" 表中查询的内容:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
?
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
?
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden

DELETE 实例

以下 SQL 语句从 客户(customer) 表中删除客户?"Alfreds Futterkiste"

【实例】

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

客户(Customers) 表现在如下所示:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
?
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden

删除所有行

可以在不删除表的情况下删除所有的行。这意味着表的结构、属性和索引都是完整的:

DELETE FROM table_name;

以下 SQL 语句删除 "Customers" 表中的所有行,而不删除该表:

【实例】

DELETE FROM Customers;

SQL?TOP, LIMIT, ROWNUM?子句

TOP 子句

TOP 子句用于规定要返回的记录的数目。

TOP 子句对于包含数千条记录的大型表很有用。返回大量记录可能会影响性能。

注:?并非所有数据库系统都支持 SELECT TOP子句。MySQL 使用 LIMIT,而 Oracle 使用 ROWNUM。

【SQL Server / MS Access 的语法:】

SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

MySQL 语法:

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Oracle 语法:

SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

演示数据库

以下是从示例数据库的 "客户(Customers)" 表中查询的内容:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
?
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
?
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden

SQL TOP、LIMIT 和 ROWNUM 示例

以下 SQL 语句从 "Customers" 表中选择前三条记录(用于 SQL Server/MS Access):

【实例】

SELECT TOP 3 * FROM Customers;

下面的 SQL 语句显示使用 LIMIT 子句的等效示例(用于 MySQL):

【实例】

SELECT * FROM Customers
LIMIT 3;

下面的 SQL 语句显示使用 ROWNUM 子句的等效示例(用于 Oracle):

【实例】

SELECT * FROM Customers
WHERE ROWNUM <= 3;

SQL TOP PERCENT 实例

在 Microsoft SQL Server 中还可以使用百分比作为参数。

以下 SQL 语句从 "Customers" 表中选择前 50% 的记录(用于SQL Server/MS Access):

【实例】

SELECT TOP 50 PERCENT * FROM Customers;

添加WHERE子句

以下 SQL 语句从 "Customers" 表中选择前三条记录,其中 country 为 "Germany"(用于SQL Server/MS Access):

【实例】

SELECT TOP 3 * FROM Customers
WHERE Country='Germany';

下面的 SQL 语句显示了使用 LIMIT 子句的等效示例(用于 MySQL):

【实例】

SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

下面的 SQL 语句显示了使用 ROWNUM 子句的等效示例(用于 Oracle):

【实例】

SELECT * FROM Customers
WHERE Country='Germany' AND ROWNUM <= 3;

SQL?MIN() 和 MAX()?函数

MIN() 和 MAX() 函数

MIN 函数返回一列中的最小值。NULL 值不包括在计算中。

MAX 函数返回一列中的最大值。NULL 值不包括在计算中。

【MIN() 语法】

SELECT MIN(column_name)
FROM table_name
WHERE condition;

【MAX() 语法】

SELECT MAX(column_name)
FROM table_name
WHERE condition;

演示数据库

以下是从示例数据库的 "Products" 表中选择的内容:

ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18
2Chang1124 - 12 oz bottles19
3Aniseed Syrup1212 - 550 ml bottles10
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22
5Chef Anton's Gumbo Mix2236 boxes21.35

MIN() 实例

以下 SQL 语句查找最便宜产品的价格:

【实例】

SELECT MIN(Price) AS SmallestPrice
FROM Products;

MAX() 实例

以下 SQL 语句查找最昂贵产品的价格:

【实例】

SELECT MAX(Price) AS LargestPrice
FROM Products;

SQL?COUNT(), AVG() 和 SUM()?函数

COUNT(), AVG() 和 SUM() 函数

COUNT() 函数返回匹配指定条件的行数。

AVG 函数返回数值列的平均值。NULL 值不包括在计算中。

SUM 函数返回数值列的总数(总额)。

【COUNT() 语法】

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

【AVG() 语法】

SELECT AVG(column_name)
FROM table_name
WHERE condition;

【SUM() 语法】

SELECT SUM(column_name)
FROM table_name
WHERE condition;

演示数据库

以下是从示例数据库的 "Products" 表中选择的内容:

ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18
2Chang1124 - 12 oz bottles19
3Aniseed Syrup1212 - 550 ml bottles10
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22
5Chef Anton's Gumbo Mix2236 boxes21.35

COUNT() 实例

以下 SQL 语句查找产品的数量:

【实例】

SELECT COUNT(ProductID)
FROM Products;

注:?不计算 NULL 空值。

AVG() 实例

以下 SQL 语句查找所有产品的平均价格:

【实例】

SELECT AVG(Price)
FROM Products;

注:?忽略 NULL 空值。

演示数据库

以下是从示例数据库的 "OrderDetails" 表中选择的内容:

OrderDetailIDOrderIDProductIDQuantity
1102481112
2102484210
310248725
410249149
5102495140

SUM() 实例

以下 SQL 语句查找 "OrderDetails" 表中 "Quantity" 字段的总和:

【实例】

SELECT SUM(Quantity)
FROM OrderDetails;

注:?忽略 NULL 空值。

SQL?LIKE?操作符

SQL LIKE 操作符

LIKE 操作符在 WHERE 子句中用于搜索列中的指定模式。

有两个通配符经常与 LIKE 操作符一起使用:

  • % - 百分号表示零个、一个或多个字符
  • _ - 下划线表示单个字符

注:?MS Access使用星号 (*) 代替百分号 (%),使用问号 (?) 代替下划线 (_)。百分号和下划线也可以组合使用!

【LIKE 语法】

SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

注:?还可以使用 AND 或 OR 运算符组合任意数量的条件。

以下是一些示例,显示了使用'%' 和 '_'通配符的不同 LIKE 运算符:

LIKE Operator描述
WHERE CustomerName LIKE 'a%'Finds any values that start with "a"
WHERE CustomerName LIKE '%a'Finds any values that end with "a"
WHERE CustomerName LIKE '%or%'Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%'Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%'Finds any values that start with "a" and are at least 2 characters in length
WHERE CustomerName LIKE 'a__%'Finds any values that start with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o'Finds any values that start with "a" and ends with "o"

演示数据库

下表显示了样本数据库中完整的客户(Customers) 表:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden
6Blauer See DelikatessenHanna MoosForsterstr. 57Mannheim68306Germany
7Blondel père et filsFrédérique Citeaux24, place KléberStrasbourg67000France
8Bólido Comidas preparadasMartín SommerC/ Araquil, 67Madrid28023Spain
9Bon app'Laurence Lebihans12, rue des BouchersMarseille13008France
10Bottom-Dollar MarketseElizabeth Lincoln23 Tsawassen Blvd.TsawassenT2F 8M4Canada
11B's BeveragesVictoria AshworthFauntleroy CircusLondonEC2 5NTUK
12Cactus Comidas para llevarPatricio SimpsonCerrito 333Buenos Aires1010Argentina
13Centro comercial MoctezumaFrancisco ChangSierras de Granada 9993México D.F.05022Mexico
14Chop-suey ChineseYang WangHauptstr. 29Bern3012Switzerland
15Comércio MineiroPedro AfonsoAv. dos Lusíadas, 23S?o Paulo05432-043Brazil
16Consolidated HoldingsElizabeth BrownBerkeley Gardens 12 BreweryLondonWX1 6LTUK
17Drachenblut DelikatessendSven OttliebWalserweg 21Aachen52066Germany
18Du monde entierJanine Labrune67, rue des Cinquante OtagesNantes44000France
19Eastern ConnectionAnn Devon35 King GeorgeLondonWX3 6FWUK
20Ernst HandelRoland MendelKirchgasse 6Graz8010Austria
21Familia ArquibaldoAria CruzRua Orós, 92S?o Paulo05442-030Brazil
22FISSA Fabrica Inter. Salchichas S.A.Diego RoelC/ Moralzarzal, 86Madrid28034Spain
23Folies gourmandesMartine Rancé184, chaussée de TournaiLille59000France
24Folk och f? HBMaria Larsson?kergatan 24Br?ckeS-844 67Sweden
25FrankenversandPeter FrankenBerliner Platz 43München80805Germany
26France restaurationCarine Schmitt54, rue RoyaleNantes44000France
27Franchi S.p.A.Paolo AccortiVia Monte Bianco 34Torino10100Italy
28Furia Bacalhau e Frutos do MarLino RodriguezJardim das rosas n. 32Lisboa1675Portugal
29Galería del gastrónomoEduardo SaavedraRambla de Catalu?a, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
31Gourmet LanchonetesAndré FonsecaAv. Brasil, 442Campinas04876-786Brazil
32Great Lakes Food MarketHoward Snyder2732 Baker Blvd.Eugene97403USA
33GROSELLA-RestauranteManuel Pereira5a Ave. Los Palos GrandesCaracas1081Venezuela
34Hanari CarnesMario PontesRua do Pa?o, 67Rio de Janeiro05454-876Brazil
35HILARIóN-AbastosCarlos HernándezCarrera 22 con Ave. Carlos Soublette #8-35San Cristóbal5022Venezuela
36Hungry Coyote Import StoreYoshi LatimerCity Center Plaza 516 Main St.Elgin97827USA
37Hungry Owl All-Night GrocersPatricia McKenna8 Johnstown RoadCorkIreland
38Island TradingHelen BennettGarden House Crowther WayCowesPO31 7PJUK
39K?niglich EssenPhilip CramerMaubelstr. 90Brandenburg14776Germany
40La corne d'abondanceDaniel Tonini67, avenue de l'EuropeVersailles78000France
41La maison d'AsieAnnette Roulet1 rue Alsace-LorraineToulouse31000France
42Laughing Bacchus Wine CellarsYoshi Tannamuri1900 Oak St.VancouverV3F 2K1Canada
43Lazy K Kountry StoreJohn Steel12 Orchestra TerraceWalla Walla99362USA
44Lehmanns MarktstandRenate MessnerMagazinweg 7Frankfurt a.M.60528Germany
45Let's Stop N ShopJaime Yorres87 Polk St. Suite 5San Francisco94117USA
46LILA-SupermercadoCarlos GonzálezCarrera 52 con Ave. Bolívar #65-98 Llano LargoBarquisimeto3508Venezuela
47LINO-DelicatesesFelipe IzquierdoAve. 5 de Mayo PorlamarI. de Margarita4980Venezuela
48Lonesome Pine RestaurantFran Wilson89 Chiaroscuro Rd.Portland97219USA
49Magazzini Alimentari RiunitiGiovanni RovelliVia Ludovico il Moro 22Bergamo24100Italy
50Maison DeweyCatherine DeweyRue Joseph-Bens 532BruxellesB-1180Belgium
51Mère PaillardeJean Fresnière43 rue St. LaurentMontréalH1J 1C3Canada
52Morgenstern GesundkostAlexander FeuerHeerstr. 22Leipzig04179Germany
53North/SouthSimon CrowtherSouth House 300 QueensbridgeLondonSW7 1RZUK
54Océano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-ABuenos Aires1010Argentina
55Old World DelicatessenRene Phillips2743 Bering St.Anchorage99508USA
56Ottilies K?seladenHenriette PfalzheimMehrheimerstr. 369K?ln50739Germany
57Paris spécialitésMarie Bertrand265, boulevard CharonneParis75012France
58Pericles Comidas clásicasGuillermo FernándezCalle Dr. Jorge Cash 321México D.F.05033Mexico
59Piccolo und mehrGeorg PippsGeislweg 14Salzburg5020Austria
60Princesa Isabel VinhossIsabel de CastroEstrada da saúde n. 58Lisboa1756Portugal
61Que DelíciaBernardo BatistaRua da Panificadora, 12Rio de Janeiro02389-673Brazil
62Queen CozinhaLúcia CarvalhoAlameda dos Canàrios, 891S?o Paulo05487-020Brazil
63QUICK-StopHorst KlossTaucherstra?e 10Cunewalde01307Germany
64Rancho grandeSergio GutiérrezAv. del Libertador 900Buenos Aires1010Argentina
65Rattlesnake Canyon GroceryPaula Wilson2817 Milton Dr.Albuquerque87110USA
66Reggiani CaseificiMaurizio MoroniStrada Provinciale 124Reggio Emilia42100Italy
67Ricardo AdocicadosJanete LimeiraAv. Copacabana, 267Rio de Janeiro02389-890Brazil
68Richter SupermarktMichael HolzGrenzacherweg 237Genève1203Switzerland
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
70Santé GourmetJonas BergulfsenErling Skakkes gate 78Stavern4110Norway
71Save-a-lot MarketsJose Pavarotti187 Suffolk Ln.Boise83720USA
72Seven Seas ImportsHari Kumar90 Wadhurst Rd.LondonOX15 4NBUK
73Simons bistroJytte PetersenVinb?ltet 34K?benhavn1734Denmark
74Spécialités du mondeDominique Perrier25, rue LauristonParis75016France
75Split Rail Beer & AleArt BraunschweigerP.O. Box 555Lander82520USA
76Suprêmes délicesPascale CartrainBoulevard Tirou, 255CharleroiB-6000Belgium
77The Big CheeseLiz Nixon89 Jefferson Way Suite 2Portland97201USA
78The Cracker BoxLiu Wong55 Grizzly Peak Rd.Butte59801USA
79Toms Spezialit?tenKarin JosephsLuisenstr. 48Münster44087Germany
80Tortuga RestauranteMiguel Angel PaolinoAvda. Azteca 123México D.F.05033Mexico
81Tradi??o HipermercadosAnabela DominguesAv. Inês de Castro, 414S?o Paulo05634-030Brazil
82Trail's Head Gourmet ProvisionersHelvetius Nagy722 DaVinci Blvd.Kirkland98034USA
83VaffeljernetPalle IbsenSmagsl?get 45?rhus8200Denmark
84Victuailles en stockMary Saveley2, rue du CommerceLyon69004France
85Vins et alcools ChevalierPaul Henriot59 rue de l'AbbayeReims51100France
86Die Wandernde KuhRita MüllerAdenauerallee 900Stuttgart70563Germany
87Wartian HerkkuPirkko KoskitaloTorikatu 38Oulu90110Finland
88Wellington ImportadoraPaula ParenteRua do Mercado, 12Resende08737-363Brazil
89White Clover MarketsKarl Jablonski305 - 14th Ave. S. Suite 3BSeattle98128USA
90Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91WolskiZbyszekul. Filtrowa 68Walla01-012Poland

LIKE 操作符实例

以下 SQL 语句选择 CustomerName 以 "a" 开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

以下 SQL 语句选择 CustomerName 以 "a" 结尾的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

下面的 SQL 语句选择 CustomerName 中任何位置都有 "or" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

下面的 SQL 语句选择 CustomerName 第二个位置有 "r" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

以下 SQL 语句选择 CustomerName 以 "a" 开头且长度至少为3个字符的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

以下 SQL 语句选择 ContactName 以 "a" 开头、以 "o" 结尾的所有客户:

【实例】

SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

以下 SQL 语句选择 CustomerName 不以 "a" 开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

SQL?通配符

SQL 通配符

通配符可用于替代字符串中的任何其他字符。

?
通配符与?SQL LIKE?运算符一起使用。LIKE 运算符在 WHERE 子句中用于搜索列中的指定模式。

【MS Access中的通配符】

Symbol描述例子
*代表零个或多个字符bl* finds bl, black, blue, and blob
?代表单个字符h?t finds hot, hat, and hit
[]表示括号内的任意单个字符h[oa]t finds hot and hat, but not hit
!代表任何不在括号内的字符h[!oa]t finds hit, but not hot and hat
-代表一系列字符c[a-b]t finds cat and cbt
#表示任意单个数字字符2#5 finds 205, 215, 225, 235, 245, 255, 265, 275, 285, and 295

【SQL Server 中的通配符】

Symbol描述例子
%代表零个或多个字符bl% finds bl, black, blue, and blob
_代表单个字符h_t finds hot, hat, and hit
[]表示括号内的任意单个字符h[oa]t finds hot and hat, but not hit
^代表任何不在括号内的字符h[^oa]t finds hit, but not hot and hat
-代表一系列字符c[a-b]t finds cat and cbt

所有通配符也可以组合使用!

以下是一些示例,显示了 LIKE 运算符使用 '%' 和 '_' 通配符的不同:

LIKE 操作符描述
WHERE CustomerName LIKE 'a%'Finds any values that starts with "a"
WHERE CustomerName LIKE '%a'Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%'Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%'Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%'Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o'Finds any values that starts with "a" and ends with "o"

演示数据库

下表显示了样本数据库中完整的客户(Customers) 表:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden
6Blauer See DelikatessenHanna MoosForsterstr. 57Mannheim68306Germany
7Blondel père et filsFrédérique Citeaux24, place KléberStrasbourg67000France
8Bólido Comidas preparadasMartín SommerC/ Araquil, 67Madrid28023Spain
9Bon app'Laurence Lebihans12, rue des BouchersMarseille13008France
10Bottom-Dollar MarketseElizabeth Lincoln23 Tsawassen Blvd.TsawassenT2F 8M4Canada
11B's BeveragesVictoria AshworthFauntleroy CircusLondonEC2 5NTUK
12Cactus Comidas para llevarPatricio SimpsonCerrito 333Buenos Aires1010Argentina
13Centro comercial MoctezumaFrancisco ChangSierras de Granada 9993México D.F.05022Mexico
14Chop-suey ChineseYang WangHauptstr. 29Bern3012Switzerland
15Comércio MineiroPedro AfonsoAv. dos Lusíadas, 23S?o Paulo05432-043Brazil
16Consolidated HoldingsElizabeth BrownBerkeley Gardens 12 BreweryLondonWX1 6LTUK
17Drachenblut DelikatessendSven OttliebWalserweg 21Aachen52066Germany
18Du monde entierJanine Labrune67, rue des Cinquante OtagesNantes44000France
19Eastern ConnectionAnn Devon35 King GeorgeLondonWX3 6FWUK
20Ernst HandelRoland MendelKirchgasse 6Graz8010Austria
21Familia ArquibaldoAria CruzRua Orós, 92S?o Paulo05442-030Brazil
22FISSA Fabrica Inter. Salchichas S.A.Diego RoelC/ Moralzarzal, 86Madrid28034Spain
23Folies gourmandesMartine Rancé184, chaussée de TournaiLille59000France
24Folk och f? HBMaria Larsson?kergatan 24Br?ckeS-844 67Sweden
25FrankenversandPeter FrankenBerliner Platz 43München80805Germany
26France restaurationCarine Schmitt54, rue RoyaleNantes44000France
27Franchi S.p.A.Paolo AccortiVia Monte Bianco 34Torino10100Italy
28Furia Bacalhau e Frutos do MarLino RodriguezJardim das rosas n. 32Lisboa1675Portugal
29Galería del gastrónomoEduardo SaavedraRambla de Catalu?a, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
31Gourmet LanchonetesAndré FonsecaAv. Brasil, 442Campinas04876-786Brazil
32Great Lakes Food MarketHoward Snyder2732 Baker Blvd.Eugene97403USA
33GROSELLA-RestauranteManuel Pereira5a Ave. Los Palos GrandesCaracas1081Venezuela
34Hanari CarnesMario PontesRua do Pa?o, 67Rio de Janeiro05454-876Brazil
35HILARIóN-AbastosCarlos HernándezCarrera 22 con Ave. Carlos Soublette #8-35San Cristóbal5022Venezuela
36Hungry Coyote Import StoreYoshi LatimerCity Center Plaza 516 Main St.Elgin97827USA
37Hungry Owl All-Night GrocersPatricia McKenna8 Johnstown RoadCorkIreland
38Island TradingHelen BennettGarden House Crowther WayCowesPO31 7PJUK
39K?niglich EssenPhilip CramerMaubelstr. 90Brandenburg14776Germany
40La corne d'abondanceDaniel Tonini67, avenue de l'EuropeVersailles78000France
41La maison d'AsieAnnette Roulet1 rue Alsace-LorraineToulouse31000France
42Laughing Bacchus Wine CellarsYoshi Tannamuri1900 Oak St.VancouverV3F 2K1Canada
43Lazy K Kountry StoreJohn Steel12 Orchestra TerraceWalla Walla99362USA
44Lehmanns MarktstandRenate MessnerMagazinweg 7Frankfurt a.M.60528Germany
45Let's Stop N ShopJaime Yorres87 Polk St. Suite 5San Francisco94117USA
46LILA-SupermercadoCarlos GonzálezCarrera 52 con Ave. Bolívar #65-98 Llano LargoBarquisimeto3508Venezuela
47LINO-DelicatesesFelipe IzquierdoAve. 5 de Mayo PorlamarI. de Margarita4980Venezuela
48Lonesome Pine RestaurantFran Wilson89 Chiaroscuro Rd.Portland97219USA
49Magazzini Alimentari RiunitiGiovanni RovelliVia Ludovico il Moro 22Bergamo24100Italy
50Maison DeweyCatherine DeweyRue Joseph-Bens 532BruxellesB-1180Belgium
51Mère PaillardeJean Fresnière43 rue St. LaurentMontréalH1J 1C3Canada
52Morgenstern GesundkostAlexander FeuerHeerstr. 22Leipzig04179Germany
53North/SouthSimon CrowtherSouth House 300 QueensbridgeLondonSW7 1RZUK
54Océano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-ABuenos Aires1010Argentina
55Old World DelicatessenRene Phillips2743 Bering St.Anchorage99508USA
56Ottilies K?seladenHenriette PfalzheimMehrheimerstr. 369K?ln50739Germany
57Paris spécialitésMarie Bertrand265, boulevard CharonneParis75012France
58Pericles Comidas clásicasGuillermo FernándezCalle Dr. Jorge Cash 321México D.F.05033Mexico
59Piccolo und mehrGeorg PippsGeislweg 14Salzburg5020Austria
60Princesa Isabel VinhossIsabel de CastroEstrada da saúde n. 58Lisboa1756Portugal
61Que DelíciaBernardo BatistaRua da Panificadora, 12Rio de Janeiro02389-673Brazil
62Queen CozinhaLúcia CarvalhoAlameda dos Canàrios, 891S?o Paulo05487-020Brazil
63QUICK-StopHorst KlossTaucherstra?e 10Cunewalde01307Germany
64Rancho grandeSergio GutiérrezAv. del Libertador 900Buenos Aires1010Argentina
65Rattlesnake Canyon GroceryPaula Wilson2817 Milton Dr.Albuquerque87110USA
66Reggiani CaseificiMaurizio MoroniStrada Provinciale 124Reggio Emilia42100Italy
67Ricardo AdocicadosJanete LimeiraAv. Copacabana, 267Rio de Janeiro02389-890Brazil
68Richter SupermarktMichael HolzGrenzacherweg 237Genève1203Switzerland
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
70Santé GourmetJonas BergulfsenErling Skakkes gate 78Stavern4110Norway
71Save-a-lot MarketsJose Pavarotti187 Suffolk Ln.Boise83720USA
72Seven Seas ImportsHari Kumar90 Wadhurst Rd.LondonOX15 4NBUK
73Simons bistroJytte PetersenVinb?ltet 34K?benhavn1734Denmark
74Spécialités du mondeDominique Perrier25, rue LauristonParis75016France
75Split Rail Beer & AleArt BraunschweigerP.O. Box 555Lander82520USA
76Suprêmes délicesPascale CartrainBoulevard Tirou, 255CharleroiB-6000Belgium
77The Big CheeseLiz Nixon89 Jefferson Way Suite 2Portland97201USA
78The Cracker BoxLiu Wong55 Grizzly Peak Rd.Butte59801USA
79Toms Spezialit?tenKarin JosephsLuisenstr. 48Münster44087Germany
80Tortuga RestauranteMiguel Angel PaolinoAvda. Azteca 123México D.F.05033Mexico
81Tradi??o HipermercadosAnabela DominguesAv. Inês de Castro, 414S?o Paulo05634-030Brazil
82Trail's Head Gourmet ProvisionersHelvetius Nagy722 DaVinci Blvd.Kirkland98034USA
83VaffeljernetPalle IbsenSmagsl?get 45?rhus8200Denmark
84Victuailles en stockMary Saveley2, rue du CommerceLyon69004France
85Vins et alcools ChevalierPaul Henriot59 rue de l'AbbayeReims51100France
86Die Wandernde KuhRita MüllerAdenauerallee 900Stuttgart70563Germany
87Wartian HerkkuPirkko KoskitaloTorikatu 38Oulu90110Finland
88Wellington ImportadoraPaula ParenteRua do Mercado, 12Resende08737-363Brazil
89White Clover MarketsKarl Jablonski305 - 14th Ave. S. Suite 3BSeattle98128USA
90Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91WolskiZbyszekul. Filtrowa 68Walla01-012Poland

使用 % 通配符

以下SQL语句选择城市以 "ber" 开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE 'ber%';

以下 SQL 语句选择城市中包含模式 "es" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE '%es%';

使用 _ 通配符

以下 SQL 语句选择城市以任意字符开头,后跟 "ondon" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE '_ondon';

以下 SQL 语句选择城市以"L"开头、后跟任意字符、后跟"n"、后跟任意字符、后跟"on"的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

使用 [charlist] 通配符

以下 SQL 语句选择城市以"b"、"s"或"p"开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE '[bsp]%';

以下 SQL 语句选择城市以"a"、"b"或"c"开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE '[a-c]%';

使用 [!charlist] 通配符

以下两条SQL语句选择城市不以"b"、"s"或"p"开头的所有客户:

【实例】

SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

或者:

【实例】

SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';

SQL?IN?操作符

SQL IN 操作符

IN 操作符允许我们在 WHERE 子句中规定多个值。

IN 操作符是多个OR条件的简写。

【IN 语法】

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

或者:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

演示数据库

下表显示了样本数据库中完整的客户(Customers) 表:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbk?pChristina BerglundBerguvsv?gen 8Lule?S-958 22Sweden
6Blauer See DelikatessenHanna MoosForsterstr. 57Mannheim68306Germany
7Blondel père et filsFrédérique Citeaux24, place KléberStrasbourg67000France
8Bólido Comidas preparadasMartín SommerC/ Araquil, 67Madrid28023Spain
9Bon app'Laurence Lebihans12, rue des BouchersMarseille13008France
10Bottom-Dollar MarketseElizabeth Lincoln23 Tsawassen Blvd.TsawassenT2F 8M4Canada
11B's BeveragesVictoria AshworthFauntleroy CircusLondonEC2 5NTUK
12Cactus Comidas para llevarPatricio SimpsonCerrito 333Buenos Aires1010Argentina
13Centro comercial MoctezumaFrancisco ChangSierras de Granada 9993México D.F.05022Mexico
14Chop-suey ChineseYang WangHauptstr. 29Bern3012Switzerland
15Comércio MineiroPedro AfonsoAv. dos Lusíadas, 23S?o Paulo05432-043Brazil
16Consolidated HoldingsElizabeth BrownBerkeley Gardens 12 BreweryLondonWX1 6LTUK
17Drachenblut DelikatessendSven OttliebWalserweg 21Aachen52066Germany
18Du monde entierJanine Labrune67, rue des Cinquante OtagesNantes44000France
19Eastern ConnectionAnn Devon35 King GeorgeLondonWX3 6FWUK
20Ernst HandelRoland MendelKirchgasse 6Graz8010Austria
21Familia ArquibaldoAria CruzRua Orós, 92S?o Paulo05442-030Brazil
22FISSA Fabrica Inter. Salchichas S.A.Diego RoelC/ Moralzarzal, 86Madrid28034Spain
23Folies gourmandesMartine Rancé184, chaussée de TournaiLille59000France
24Folk och f? HBMaria Larsson?kergatan 24Br?ckeS-844 67Sweden
25FrankenversandPeter FrankenBerliner Platz 43München80805Germany
26France restaurationCarine Schmitt54, rue RoyaleNantes44000France
27Franchi S.p.A.Paolo AccortiVia Monte Bianco 34Torino10100Italy
28Furia Bacalhau e Frutos do MarLino RodriguezJardim das rosas n. 32Lisboa1675Portugal
29Galería del gastrónomoEduardo SaavedraRambla de Catalu?a, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
31Gourmet LanchonetesAndré FonsecaAv. Brasil, 442Campinas04876-786Brazil
32Great Lakes Food MarketHoward Snyder2732 Baker Blvd.Eugene97403USA
33GROSELLA-RestauranteManuel Pereira5a Ave. Los Palos GrandesCaracas1081Venezuela
34Hanari CarnesMario PontesRua do Pa?o, 67Rio de Janeiro05454-876Brazil
35HILARIóN-AbastosCarlos HernándezCarrera 22 con Ave. Carlos Soublette #8-35San Cristóbal5022Venezuela
36Hungry Coyote Import StoreYoshi LatimerCity Center Plaza 516 Main St.Elgin97827USA
37Hungry Owl All-Night GrocersPatricia McKenna8 Johnstown RoadCorkIreland
38Island TradingHelen BennettGarden House Crowther WayCowesPO31 7PJUK
39K?niglich EssenPhilip CramerMaubelstr. 90Brandenburg14776Germany
40La corne d'abondanceDaniel Tonini67, avenue de l'EuropeVersailles78000France
41La maison d'AsieAnnette Roulet1 rue Alsace-LorraineToulouse31000France
42Laughing Bacchus Wine CellarsYoshi Tannamuri1900 Oak St.VancouverV3F 2K1Canada
43Lazy K Kountry StoreJohn Steel12 Orchestra TerraceWalla Walla99362USA
44Lehmanns MarktstandRenate MessnerMagazinweg 7Frankfurt a.M.60528Germany
45Let's Stop N ShopJaime Yorres87 Polk St. Suite 5San Francisco94117USA
46LILA-SupermercadoCarlos GonzálezCarrera 52 con Ave. Bolívar #65-98 Llano LargoBarquisimeto3508Venezuela
47LINO-DelicatesesFelipe IzquierdoAve. 5 de Mayo PorlamarI. de Margarita4980Venezuela
48Lonesome Pine RestaurantFran Wilson89 Chiaroscuro Rd.Portland97219USA
49Magazzini Alimentari RiunitiGiovanni RovelliVia Ludovico il Moro 22Bergamo24100Italy
50Maison DeweyCatherine DeweyRue Joseph-Bens 532BruxellesB-1180Belgium
51Mère PaillardeJean Fresnière43 rue St. LaurentMontréalH1J 1C3Canada
52Morgenstern GesundkostAlexander FeuerHeerstr. 22Leipzig04179Germany
53North/SouthSimon CrowtherSouth House 300 QueensbridgeLondonSW7 1RZUK
54Océano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-ABuenos Aires1010Argentina
55Old World DelicatessenRene Phillips2743 Bering St.Anchorage99508USA
56Ottilies K?seladenHenriette PfalzheimMehrheimerstr. 369K?ln50739Germany
57Paris spécialitésMarie Bertrand265, boulevard CharonneParis75012France
58Pericles Comidas clásicasGuillermo FernándezCalle Dr. Jorge Cash 321México D.F.05033Mexico
59Piccolo und mehrGeorg PippsGeislweg 14Salzburg5020Austria
60Princesa Isabel VinhossIsabel de CastroEstrada da saúde n. 58Lisboa1756Portugal
61Que DelíciaBernardo BatistaRua da Panificadora, 12Rio de Janeiro02389-673Brazil
62Queen CozinhaLúcia CarvalhoAlameda dos Canàrios, 891S?o Paulo05487-020Brazil
63QUICK-StopHorst KlossTaucherstra?e 10Cunewalde01307Germany
64Rancho grandeSergio GutiérrezAv. del Libertador 900Buenos Aires1010Argentina
65Rattlesnake Canyon GroceryPaula Wilson2817 Milton Dr.Albuquerque87110USA
66Reggiani CaseificiMaurizio MoroniStrada Provinciale 124Reggio Emilia42100Italy
67Ricardo AdocicadosJanete LimeiraAv. Copacabana, 267Rio de Janeiro02389-890Brazil
68Richter SupermarktMichael HolzGrenzacherweg 237Genève1203Switzerland
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
70Santé GourmetJonas BergulfsenErling Skakkes gate 78Stavern4110Norway
71Save-a-lot MarketsJose Pavarotti187 Suffolk Ln.Boise83720USA
72Seven Seas ImportsHari Kumar90 Wadhurst Rd.LondonOX15 4NBUK
73Simons bistroJytte PetersenVinb?ltet 34K?benhavn1734Denmark
74Spécialités du mondeDominique Perrier25, rue LauristonParis75016France
75Split Rail Beer & AleArt BraunschweigerP.O. Box 555Lander82520USA
76Suprêmes délicesPascale CartrainBoulevard Tirou, 255CharleroiB-6000Belgium
77The Big CheeseLiz Nixon89 Jefferson Way Suite 2Portland97201USA
78The Cracker BoxLiu Wong55 Grizzly Peak Rd.Butte59801USA
79Toms Spezialit?tenKarin JosephsLuisenstr. 48Münster44087Germany
80Tortuga RestauranteMiguel Angel PaolinoAvda. Azteca 123México D.F.05033Mexico
81Tradi??o HipermercadosAnabela DominguesAv. Inês de Castro, 414S?o Paulo05634-030Brazil
82Trail's Head Gourmet ProvisionersHelvetius Nagy722 DaVinci Blvd.Kirkland98034USA
83VaffeljernetPalle IbsenSmagsl?get 45?rhus8200Denmark
84Victuailles en stockMary Saveley2, rue du CommerceLyon69004France
85Vins et alcools ChevalierPaul Henriot59 rue de l'AbbayeReims51100France
86Die Wandernde KuhRita MüllerAdenauerallee 900Stuttgart70563Germany
87Wartian HerkkuPirkko KoskitaloTorikatu 38Oulu90110Finland
88Wellington ImportadoraPaula ParenteRua do Mercado, 12Resende08737-363Brazil
89White Clover MarketsKarl Jablonski305 - 14th Ave. S. Suite 3BSeattle98128USA
90Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91WolskiZbyszekul. Filtrowa 68Walla01-012Poland

IN 操作符实例

以下 SQL 语句选择位于 "Germany", "France", "UK" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

以下 SQL 语句选择不在 "Germany", "France" or "UK" 的所有客户:

【实例】

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

以下 SQL 语句选择与供应商来自相同国家/地区的所有客户:

【实例】

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

SQL?BETWEEN?操作符

SQL BETWEEN 操作符

BETWEEN 操作符在 WHERE 子句中使用,作用是选取介于两个值之间的数据范围。这些值可以是数值、文本或者日期。

BETWEEN 操作符包括开始值和结束值。

【BETWEEN 语法】

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

演示数据库

以下是从示例数据库的 产品(Products) 表中选择的内容:

ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18
2Chang1124 - 12 oz bottles19
3Aniseed Syrup1212 - 550 ml bottles10
4Chef Anton's Cajun Seasoning1248 - 6 oz jars22
5Chef Anton's Gumbo Mix1236 boxes21.35

BETWEEN 实例

以下 SQL 语句选择价格介于 10 和 20 之间的所有产品:

【实例】

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN 实例

要显示上一示例范围之外的产品,请使用 NOT BETWEEN:

【实例】

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

带有 IN 的 BETWEEN 操作符实例

下面的 SQL 语句选择价格介于 10 和 20 之间的所有产品。此外请勿显示 CategoryID 为1、2或3的产品:

【实例】

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

带有文本值的 BETWEEN 操作符实例

以下 SQL 语句选择所有产品,其产品名称介于 Carnavon Tigers 和 Mozzarella di Giovanni 之间:

【实例】

SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

以下SQL语句选择所有产品,产品名称介于 Carnarvon Tigers 和 Chef Anton's Cajun Seasoning 之间:

【实例】

SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

带有文本值的 NOT BETWEEN 操作符实例

以下SQL语句选择了所有产品,其产品名称不在 Carnarvon Tigers 和 Mozzarella di Giovanni 之间:

【实例】

SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

示例表

以下是从示例数据库的 "订单(Orders)" 表中选择的内容:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489057/4/19963
102498167/5/19961
102503447/8/19962
102518437/9/19961
102527647/10/19962

带有日期值的 BETWEEN 操作符实例

以下 SQL 语句选择 OrderDate 介于 "1996年7月1日" 和 "1996年7月31日" 之间的所有订单:

【实例】

SELECT * FROM Orders
WHERE OrderDate BETWEEN #01/07/1996# AND #31/07/1996#;

或者:

SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

SQL?别名

SQL 别名

SQL 别名用于为表或表中的列提供临时名称。

别名通常用于提高列名的可读性。

别名仅在查询期间有效。

【列的 SQL Alias 语法】

SELECT column_name AS alias_name
FROM table_name;

【表的 SQL Alias 语法】

SELECT column_name(s)
FROM table_name AS alias_name;

演示数据库

以下是从 "Customers" 表中选择的内容:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK

以及从 "Orders" 表中选择的内容:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
103545881996-11-143
10355461996-11-151
103568661996-11-182

Alias 实例: 使用一个列名别名

以下 SQL 语句创建两个别名,一个用于 CustomerID 列,另一个用于 CustomerName 列:

【实例】

SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

下面的SQL语句创建两个别名,一个用于CustomerName列,另一个用于ContactName列。

注:?如果别名包含空格,则需要双引号或方括号。

【实例】

SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;

以下 SQL 语句创建一个名为 "Address" 的别名,该别名由四列(Address、PostalCode、City和Country)组成:

【实例】

SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;

注:?要使上述 SQL 语句在 MySQL 中工作,请使用以下命令:

SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;

Alias 实例: 使用表名称别名

下面的 SQL 语句选择 CustomerID=4(Around the Horn)的客户的所有订单。我们使用 "Customers" 和 "Orders" 表,并分别为它们提供表别名 "c" 和 "o"(这里我们使用别名来缩短 SQL):

【实例】

SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

以下 SQL 语句与上面相同,但没有别名:

【实例】

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;

在下面的情况下,使用别名很有用:

  • 在查询中涉及超过一个表
  • 在查询中使用了函数
  • 列名称很长或者可读性差
  • 需要把两个列或者多个列结合在一起

SQL?联接

SQL JOIN

JOIN SQL 用于根据两个或多个表之间的一个相关列合并两个或多个表中的行。

请看 "Orders" 表:

OrderIDCustomerIDOrderDate
1030821996-09-18
10309371996-09-19
10310771996-09-20

然后,请看 "Customers" 表:

CustomerIDCustomerNameContactNameCountry
1Alfreds FutterkisteMaria AndersGermany
2Ana Trujillo Emparedados y heladosAna TrujilloMexico
3Antonio Moreno TaqueríaAntonio MorenoMexico

请注意,"Customers" 表中的 "CustomerID" 列指的是 "Customers" 表中的 "CustomerID"。上面两个表之间的关系是 "CustomerID" 列。

然后,我们可以创建以下 SQL 语句(包含 INNER JOIN),用于选择两个表中具有匹配值的记录:

【实例】

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

将产生如下结果:

OrderIDCustomerNameOrderDate
10308Ana Trujillo Emparedados y helados9/18/1996
10365Antonio Moreno Taquería11/27/1996
10383Around the Horn12/16/1996
10355Around the Horn11/15/1996
10278Berglunds snabbk?p8/12/1996

不同类型的 SQL JOIN

下面列出了您可以使用的 JOIN 类型,以及它们之间的差异。

  • (INNER) JOIN: 如果表中有至少一个匹配,则返回行
  • LEFT (OUTER) JOIN: 即使右表中没有匹配,也从左表返回所有的行
  • RIGHT (OUTER) JOIN: 即使左表中没有匹配,也从右表返回所有的行
  • FULL (OUTER) JOIN: 只要其中一个表中存在匹配,就返回行

文章来源:https://blog.csdn.net/ZK180531/article/details/135827283
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。