SQL query optimize

2019-08-19 05:54发布

问题:

In a slide http://www.slideshare.net/billkarwin/models-for-hierarchical-data, i saw a sql code (page 22):

INSERT INTO Comments (author, comment)
VALUES (‘Ollie’, ‘Good job!’);

SELECT path FROM Comments
WHERE comment_id = 7;

UPDATE Comments
SET path = $parent_path || LAST_INSERT_ID() || ‘/’
WHERE comment_id = LAST_INSERT_ID();

I think we can optimize it:

SELECT path FROM Comments
WHERE comment_id = 7;

INSERT INTO Comments (author, comment, path )
VALUES (‘Ollie’, ‘Good job!’,  $parent_path || LAST_INSERT_ID() || ‘/’);

Am I right?

回答1:

Yes, a single insert would be better than an insert followed by an update, but in this case the auto-generated id(?) is being used as a column value as well. The LAST_INSERT_ID() used in the path would not be the id of the current insert statement being performed, but that of the last (previous) insert.