向表中插入数据时,可以使用选择语句(SELECT FROM WHERE)作为插入语句(INSERT INTO)的子查询进行数据的插入
sql复制代码
-- 新增的表没有主键,也没被标记为自动递增列
CREATE TABLE orders_archived_wuxu AS
SELECT * FROM orders
-- 可以使用Truncate工具删除表中的所有数据
-- 在复制的已经被删除了所有数据的新表中,想插入2019-01-01之前的数据,可以'使用选择语句做作为插入语句中的子查询'
INSERT INTO orders_archived_wuxu
SELECT *
FROM orders
WHERE order_date < '2019-01-01'
sql复制代码
-- 小小练习
CREATE TABLE invoices_archived_wuxu AS
SELECT invoice_id,
number,
c.name,
invoice_total,
payment_total,
invoice_date,
due_date,
payment_date
FROM invoices
JOIN clients c USING (client_id)
WHERE payment_date IS NOT NULL;
更新单行 UPDATE...SET
UPDATE 表名 SET 每列信息
sql复制代码
-- 更新id为1的这列
UPDATE invoices
SET payment_total = 10, payment_date = '2019-03-01'
WHERE invoice_id = 1;
-- 把id为1的这列恢复成更新之前的
UPDATE invoices
SET payment_total = DEFAULT, payment_date = NULL
WHERE invoice_id = 1;
-- 更新id为3的这列
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE invoice_id = 3;
更新多行
在WHERE子句中选择多行更新即可
sql复制代码
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
-- WHERE子句中选择多行更新即可
WHERE client_id IN (3,4);
sql复制代码
-- 小小练习,给在1990-01-01之前的顾客加50分
USE sql_store;
UPDATE customers
SET points = points + 50
WHERE birth_date < '1990-01-01';
在UPDATES中使用子查询【需着重复习】
sql复制代码
-- 不采用硬编码指定值
USE sql_invoicing;
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
-- client_id不直接指定为几,不采用硬编码
-- 而是通过子查询来指定client_id的值
WHERE client_id =
(SELECT client_id
FROM clients
WHERE name = 'Myworks')
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
-- 多个查询条件是要换成IN
WHERE client_id IN
(SELECT client_id
FROM clients
WHERE state IN ('CA', 'NY'))
sql复制代码
-- 练习
-- 我的写法,先把orders和customers表通过id匹配
UPDATE orders
JOIN customers USING (customer_id)
SET comments = 'GoldenClient'
WHERE shipped_date IS NOT NULL AND points > 3000
-- 筛选条件中直接写子查询,这样更清楚,思路更易懂。需要学习、习惯这种写法
UPDATE orders
SET comments = 'GoldenClient'
WHERE shipped_date IS NOT NULL AND
customer_id IN (
SELECT customer_id
FROM customers
WHERE points > 3000)
删除行 DELETE
DELETE FROM
sql复制代码
DELETE FROM invoices
WHERE client_id = (
SELECT client_id
FROM clients
WHERE name = 'Myworks')