使用表别名
别名除了用于列名和计算字段外,SQL还允许给表名起别名。这样做有两个主要理由:
1、缩短SQL语句
2、允许在单挑SELECT语句中多次使用相同的表
(Oracle)写法
SELECT cust_name, cust_contact
FROM Customers C, Orders O, OrderItems OI
WHERE C.cust_id = O.cust_id
AND OI.order_num = O.order_num
AND prod_id = 'RGAN01';
自联结
SELECT c1.cust_id, c1.cust_name, c1.cist_contact
FROM Customers c1, Customers c2
WHERE c1.cust_name = c2. cust_name,
AND c2.cust_name = 'Jim Jones';
用自联结而不用子查询
自联结通常作为外部语句用来替代从相同表中检查数据的使用子查询语句。虽然最终的结果是相同的,但许多DBMS处理联结远比处理子查询快得多。
组合查询
两种基本情况,其中需要使用组合查询:
1、在单个查询中从不同的表类似返回结构数据。
2、对单个表执行多个查询,按单个查询返回数据。
使用UNION
UNION只需在每条SELECT语句之间加入关键字UNION
例:
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4F11'
此处可以用OR替换
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
OR cust_name = 'Fun4F11'
包含或取消重复的行
UNION从查询结果集中自动去除重复的行
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION ALL
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4F11'
插入数据
INSERT用于插入(或添加)行到数据库表。插入可以用几种方式使用:
1、插入完整的行
2、插入行的一部分
3、插入某些查询的结果
--插入完整行
INSERT INTO Customers
VALUES('10086',
'NY',
'mobile');
--插入部分行
INSERT INTO Customers(cust_id,
cust_name,
cust_city)
VALUES('10086',
'Jacky',
'NY');
插入检索出的数据
INSERT INTO Customers(cust_id,
cust_email,
cust_name,
cust_city)
SELECT cust_id,
cust_email,
cust_name,
cust_city
FROM CustNew;
这个例子使用INSERT SELECT从CustNew中将所有数据导入Customers.
SELECT *
INTO CustCopy
FROM Customers;
这条SELECT语句创建一个名为CustCopy的新表,并把Customers表的整个内容复制到新表中。
更新和删除数据
更新多个列的数据
UPDATE Customers
SET cust_contact = 'Sam Roberts',
cust_email = 'sam@toyland.com',
WHERE cust_id = '10086';
删除一行数据
DELETE FROM Customers
WHERE cust_id = '10086';
DELETE不需要列名或通配符。DELETE删除整行而不是删除列。为了删除指定的列,请使用UPDATE语句。