SELECT query in WHERE clause of UPDATE query [duplicate]

放肆的年华 提交于 2020-01-23 02:06:13

问题


Possible Duplicate:
Mysql error 1093 - Can’t specify target table for update in FROM clause

I am getting an error when putting SELECT query in WHERE clause of UPDATE query.

my Query is like this :

UPDATE `subschedulesseats` m
SET m.studentid='1'
WHERE m.`seatid`= (
    SELECT h.`seatid`
    FROM `subschedulesseats` h
    WHERE h.`sessiontime`='02:30~04:00'
    ORDER BY h.`seatid` ASC
    LIMIT 2,1
)

AND Error will be shown is like this :

"You can't specify target table 'm' for update in FROM clause"

I have attached a snap shot of the error display.

Please anyone can help me in this problem?

Thank You in Advance


回答1:


Actually you can update it by wrapping it in a subquery (thus creating temporary table for the result)

UPDATE `subschedulesseats` m
SET m.studentid='1'
WHERE m.`seatid`= 
(
    SELECT seatID
    FROM
    (
        SELECT h.`seatid`
        FROM `subschedulesseats` h
        WHERE h.`sessiontime`='02:30~04:00'
        ORDER BY h.`seatid` ASC
        LIMIT 2,1
    ) s
)

or by using JOIN

UPDATE  `subschedulesseats` m
        INNER JOIN
        (
            SELECT seatID
            FROM
            (
                SELECT h.`seatid`
                FROM `subschedulesseats` h
                WHERE h.`sessiontime`='02:30~04:00'
                ORDER BY h.`seatid` ASC
                LIMIT 2,1
            ) s
        ) t ON m.seatID = t.seatID
SET     m.studentid = '1'



回答2:


In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html

The reference

https://stackoverflow.com/a/45498/1225190



来源:https://stackoverflow.com/questions/13283940/select-query-in-where-clause-of-update-query

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