简体   繁体   中英

MYSQL update with inner join performance

The join is done on the primary key column of both these tables.

I have a doubt if I should fire a select query before the update or will this query be a good alternative?(in terms of performance)

order item table

order_item_id
order_id
quantity
unit_price
shipping_price
business_id
workflow_id
delivery_id
item_id

Orders table

billing_address_id
shipping_address_id
payment_mode
total_price
shipping_price
customer_id 
order_id

Following is the query I fire from my Java service (using jdbc) :

UPDATE order_items t1 
 INNER 
  JOIN Orders t2 
    ON t2.order_id = t1.order_id 
   SET t1.workflow_id = ? 
 WHERE  t1.order_item_id = ? 
   and t2.order_id = ? 
   and t2.customer_id = ? 
   and t1.delivery_id = ? 

UPDATE : Adding show create table order_items

'CREATE TABLE `order_items` (
`order_item_id` int(20) NOT NULL AUTO_INCREMENT,
`quantity` int(10) unsigned NOT NULL,
`unit_price` int(10) unsigned NOT NULL,
`shipping_price` int(10) unsigned NOT NULL,
`pickup_date` datetime DEFAULT NULL,
`create_TS` datetime DEFAULT CURRENT_TIMESTAMP,
`update_TS` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`business_id` int(10) NOT NULL,
`order_id` int(11) NOT NULL,
`item_id` int(10) unsigned NOT NULL,
`delivery_id` int(11) NOT NULL,
`workflow_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`order_item_id`),
 KEY `fk_business_id` (`business_id`),
 KEY `fk_order_id` (`order_id`),
 KEY `fk_item_id` (`item_id`),
 KEY `fk_delivery_id` (`delivery_id`),
 CONSTRAINT `fk_business_id` FOREIGN KEY (`business_id`) REFERENCES `business` (`MID`),
 CONSTRAINT `fk_delivery_id` FOREIGN KEY (`delivery_id`) REFERENCES `delivery_mode` (`delivery_id`),
 CONSTRAINT `fk_item_id` FOREIGN KEY (`item_id`) REFERENCES `item_business` (`item_id`),
CONSTRAINT `fk_order_id` FOREIGN KEY (`order_id`) REFERENCES `Orders` (`order_id`)

)

Talking in theory

You should have the minimum set of data before you do the join, so the join will actually be performed only on the data you need, and that is the case even with the update that is internally a special select and "write this data on the select"

Talking in practice

One of the job of any dbms is to perform an agressive level of optimization using database algebra and other stuff, so most of the time the time you spend in optimizing your query is actually futile because your dbms will perform the same level of optimization

So what

I would try to have the table the slimmest as possible but without getting too crazy, I performed on a aws db2.micro machine an update query on like 100k rows and it took it like 4 seconds, so in my opinion, try and see if you're getting the real result you need.

tl;dr just try and see if the speed increase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM