Thursday, May 31, 2012

MySQL lock table and subqueries

MySQL complaints when a subqueries table / alias is not locked.
But Even if we lock the table by tablename, it will still complaint on the subquery table being not locked.

Example:

select n.node_id,
    (select count(*) from node where node_aboveid=n.node_nextleftnodeid) as leftnextcnt,
    (select count(*) from node where node_aboveid=n.node_nextrightnodeid) as rightnextcnt,
    n.node_nextleftnodeid, n.node_nextleftdepth from
    node n

To solve this issue,
Every sub select table must have a alias name, different from the main table name.
Example:


select n.node_id,
    (select count(*) from node nleft where node_aboveid=n.node_nextleftnodeid) as leftnextcnt,
    (select count(*) from node nright where node_aboveid=n.node_nextrightnodeid) as rightnextcnt,
    n.node_nextleftnodeid, n.node_nextleftdepth from
    node n

And makesure to lock tables node write, node n write, node nleft write, node nright write;



No comments: