SQL query optimize

守給你的承諾、 提交于 2019-12-12 01:16:45

问题


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.



来源:https://stackoverflow.com/questions/13302187/sql-query-optimize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!