-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic_1.2_insert_update_delete
96 lines (80 loc) · 1.84 KB
/
topic_1.2_insert_update_delete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# insert a row:
insert into customers
values (
default,
'John',
'Smith',
'1991-01-01',
NULL,
'address',
'city',
'CA',
default)
insert into customers (
first_name,
last_name,
birth_date,
adress,
city,
state)
values (
'John',
'Smith',
'1991-01-01',
'address',
'city',
'CA')
# insert muliple rows:
insert into shippers (name)
values
('Shipper1'),
('Shipper2'),
('Shipper3')
# insert hierarchical data into multiple tables:
# the table order (order_id, customer_id, order_date, status, ...) and order_items (order_id, product_id, quantity, unite_price) have a parent child relationship.
# an order may have multiple order_items.
insert into orders (customer_id, order_date, status)
values (1, '2019-01-02', 1)
insert into order_items
values
(last_insert_id(), 1, 1, 2.5),
(last_insert_id(), 2, 1, 3.5)
# create a copy of table:
create table orders_archived as
select * from orders
# attributes of the above new table is ignored.
# truncate the above table and insert using subquery:
insert into orders_archived
select *
from orders
where order_date < '2019-01-01'
# update data in a single row:
update invoices
set payment_total = 10, payment_date = '2019-01-01'
where invoice_id = 1
# set one column equal to another column in the table:
update invoices
set payment_total = 10, payment_date = due_date
where invoice_id = 1
# udpate multiple rows in a table:
# set safe update in mysql workbench.
update invoices
set payment_total = invoice_total * 0.5, payment_date = due_date
where client_id in (3, 4)
# using subqueries in updates:
update invoices
set
payment_total = invoice_total * 0.5
payment_date = due_date
where client_id in (
select client_id
from clients
where name = 'Myworks'
)
# delete rows:
delete from invoices
where invoice_id = (
select *
from clients
where name = 'Myworks'
)