CREATETABLE orders_archived AS SELECT * FROM orders
通过这种方式创建的表复制会没有PK, AI这些属性
3.1 子查询
上例中的SELECT * FROM orders是子查询.
INSERT INTO也可以用子查询:
1 2 3 4
INSERTINTO orders_archived SELECT * FROM orders WHERE order_date < '2019-01-01'
orders_archived表中只有满足条件的records.
4 更新
4.1 更新单行
1 2 3
UPDATE invoices SET payment_total = 10, payment_date = '2019-03-01' WHERE invoice_id = 1
1 2 3
UPDATE invoices SET payment_total = DEFAULT, payment_date = NULL WHERE invoice_id = 1
1 2 3 4 5
UPDATE invoices SET payment_total = invoice_total * 0.5, -- 使用表达式更新 payment_date = due_date WHERE invoice_id = 3
4.2 更新多行
在MySQL workbench需要取消safe update选项才能更新多行.
1 2 3 4 5 6
UPDATE invoices SET payment_total = invoice_total * 0.5, -- 使用表达式更新 payment_date = due_date WHERE client_id = 3 -- WHERE client_id IN (3, 4)
client_id=3对应有多项record, 都会被update
4.3 在UPDATE中使用子查询
将上例改为:
1 2 3 4 5 6 7 8
UPDATE invoices SET payment_total = invoice_total * 0.5, -- 使用表达式更新 payment_date = due_date WHERE client_id = (SELECT client_id FROM clients WHEREname = 'Myworks')
如果子查询返回的是多个client_id:
1 2 3 4 5 6 7 8
UPDATE invoices SET payment_total = invoice_total * 0.5, -- 使用表达式更新 payment_date = due_date WHERE client_id IN-- 用IN (SELECT client_id FROM clients WHERE state IN ('CA', 'NY'))
⚠ 在执行查询之前, 应该先执行子查询看看对不对.
5 删除行
根据条件删除某些行
1 2
DELETEFROM invoices_archived WHERE invoice_id = 2
子查询
1 2 3 4 5
DELETEFROM invoices WHERE invoice_id = (SELECT client_id FROM clients WHEREname = 'Vinte')