SQL --- 简单的SQL查询

144 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

SQL中的数据类型

Characters

  • CHAR(n) --- fixed length
  • VARCHAR2(n) --- variable length (VARCHAR是标准SQL,VARCHAR2是Oracle提供的)

Numbers

  • INTEGER --- integers
  • NUMBER --- real numbers

Times and dates

  • DATE
  • TIMESTAMP

超长String

  • Long

SQL中的表(Tables)

  • A tuple: a record
  • A Table: a set of tuples
  • schema: the table name and its attributes
  • Product(PName, Price, Category, Manfacture)
  • Primary Key: an attribute (or a set of attributes) whose value is unique 在这里插入图片描述

简单的SQL查询

#target list选择表里的属性
SELECT {T1.Attribute 1, ...T2.Attribute 2, T3.Attribute 3....} 
#relation-list 计算表之间的cross product
FROM {relation} T1, {relation} T2... 
#qulification 按照条件筛选record
WHERE {predicates}

简单SQL查询的执行步骤

  • 计算一个SQL查询分为三步:
  • 计算relation-list的corss-product
  • 按照qulification筛选数据
  • 删除不在target-list里的属性
  • 上面的策略是最基础的,也是计算查询效率最低的方法
  • optimizer可以提高效率

Example: 在这里插入图片描述

SELECT PName, Price, Manufacture
FROM Product
WHERE Price > 100

在这里插入图片描述

在查询中链接多个表

Example 1: Product

PNamePriceCategoryManufacturer
Gizmo$19.99GadgetsGizmoWorks
Powergizmo$29.99GadgetsGizmoWorks
SingleTouch$149.99PhotographyCanon
MultiTouch$203.99HouseholdHitachi

Company

CnameStockPriceCountry
GizmoWorks25USA
Canon65Japan
Hitachi15Japan
SELECT pname, price
FROM Product, Company
WHERE manufacturer=cname AND country=‘Japan’

计算cross product

FROM Product, Company
PNamePriceCategoryManufacturerCnameStockPriceCountry
Gizmo$19.99GadgetsGizmoWorksGizmoWorks25USA
Gizmo$19.99GadgetsGizmoWorksCanon65Japan
Gizmo$19.99GadgetsGizmoWorksHitachi15Japan
Powergizmo$29.99GadgetsGizmoWorksGizmoWorks25USA
Powergizmo$29.99GadgetsGizmoWorksCanon65Japan
Powergizmo$29.99GadgetsGizmoWorksHitachi15Japan
SingleTouch$149.99PhotographyCanonGizmoWorks25USA
SingleTouch$149.99PhotographyCanonCanon65Japan
SingleTouch$149.99PhotographyCanonHitachi15Japan
MultiTouch$203.99HouseholdHitachiGizmoWorks25USA
MultiTouch$203.99HouseholdHitachiCanon65Japan
MultiTouch$203.99HouseholdHitachiHitachi15Japan

根据WHERE条件进行筛选

manufacturer=cname AND country=‘Japan’
PNamePriceCategoryManufacturerCnameStockPriceCountry
SingleTouch$149.99PhotographyCanonCanon65Japan
MultiTouch$203.99HouseholdHitachiHitachi15Japan

删除不在target list里的属性

SELECT pname, price
PNamePrice
SingleTouch$149.99
MultiTouch$203.99

Example 2: Product

PNamePriceCategoryManufacturer
Gizmo$19.99GadgetsGizmoWorks
Powergizmo$29.99GadgetsGizmoWorks
SingleTouch$149.99PhotographyCanon
MultiTouch$203.99HouseholdHitachi

Company

CnameStockPriceCountry
GizmoWorks25USA
Canon65Japan
Hitachi15Japan
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’

Answer: 会出现两个USA

Country
USA
USA

所以需要加上DISTINCT

SELECT DISTINCT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’

Example 3:

Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city)

  • Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of thestores they bought such product from
SELECT DISTINCT persname, store
FROM Person, Purchase, Product
#persname对应buyer, pname对应product
WHERE persname=buyer AND product = pname AND 
city=‘Seattle’ AND category=‘Gadgets’

Example 4:

Person(pname, address, worksfor) Company(cname, address)

SELECT DISTINCT pname, address #Person和Company中都有Address, 是哪个?
FROM Person, Company
WHERE worksfor = cname

修改为

SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname

复杂SQL查询的执行步骤

  1. The cross products of the tables in the FROM clause are evaluated.
  2. Rows not satisfying the WHERE clause are eliminated.
  3. The remaining rows are grouped in accordance with the GROUP BY clause.
  4. Groups not satisfying the HAVING clause are then eliminated.
  5. The expressions in the SELECT list are evaluated.
  6. If the keyword DISTINCT is present, duplicate rows are now eliminated.
  7. Evaluate UNION, INTERSECT and EXCEPT for Subqueries up to this point.
  8. Finally, the set of all selected rows is sorted if the ORDER BY is present.

Banking Example

branch (branch-id, branch-city, assets)
customer (customer-id, customer-name, customer-city)
account (account-number, branch-id, balance)
loan (loan-number, branch-id, amount)
depositor (customer-id, account-number)
borrower (customer-id, loan-number)

EXISTS Example 1: “Select all the account balances where the account has been opened in a branch in Fairfax”

SELECT A.account-balance
FROM account A
WHERE EXISTS (SELECT *
			  FROM branch B
              WHERE B.branch-city=‘Fairfax’
					AND B.branch-id=A.branch-id)

EXISTS Example 2: “Select all the account balances where the account has not been opened in a Fairfax branch ”

SELECTA.account-balance
FROM account A
WHERE NOT EXISTS (SELECT *
				  FROM branch B
				  WHERE B.branch-city=‘Fairfax’
				  AND B.branch-id=A.branch-id)

NOT EXISTS Example 3: “Find customers who opened accounts in all branches in Fairfax”

SELECT C.customer-id
FROM customer C
WHERE NOT EXISTS (SELECT B.branch-id
				  FROM branch B
				  WHERE B.branch-city=‘Fairfax’
				  EXCEPT
			      SELECT A.branch-id
				  FROM depositor D, account A
				  WHERE D.customer-id = C.customer-id AND
						D.account-number =A.account-number)