Updating selected rows in Firebird

喜夏-厌秋 提交于 2019-12-13 17:56:14

问题


I want to modify my query. Right now it looks like this

SELECT EW_POLYLINE.P0_X, EW_POLYLINE.P0_Y, EW_POLYLINE.ID, EW_POLYLINE.STAN_ZMIANY, a.IDE, EW_POLYLINE.ID_WARSTWY
FROM EW_POLYLINE 
LEFT JOIN (
    SELECT EW_OBIEKTY.STATUS
        , EW_OB_ELEMENTY.IDE
        , EW_OB_ELEMENTY.TYP
    FROM EW_OBIEKTY 
    INNER JOIN EW_OB_ELEMENTY 
        ON EW_OBIEKTY.UID = EW_OB_ELEMENTY.UIDO
    WHERE EW_OBIEKTY.STATUS = 0 AND EW_OB_ELEMENTY.TYP <> 1
) as a ON EW_POLYLINE.ID = a.IDE
WHERE EW_POLYLINE.STAN_ZMIANY = 0 AND a.IDE Is Null

Right now it returns like 1/3 of database, and I want to modify "stan_zmiany" of these rows to 3. Since I can not use UPDATE FROM construction in Firebird I tried

update EW_POLYLINE
set stan_zmiany = 3
WHERE EXISTS (SELECT 1
FROM EW_POLYLINE 
LEFT JOIN (
    SELECT EW_OBIEKTY.STATUS
        , EW_OB_ELEMENTY.IDE
        , EW_OB_ELEMENTY.TYP
    FROM EW_OBIEKTY 
    INNER JOIN EW_OB_ELEMENTY 
        ON EW_OBIEKTY.UID = EW_OB_ELEMENTY.UIDO
    WHERE EW_OBIEKTY.STATUS = 0 AND EW_OB_ELEMENTY.TYP <> 1
) as a ON EW_POLYLINE.ID = a.IDE
where EW_POLYLINE.STAN_ZMIANY = 0 AND a.IDE Is Null)

but it change "stan_zmiany" for all rows, not for selected in first query, do you know how to fix this?


回答1:


Your sub-query in the exists is an uncorrelated sub-query, which means it doesn't depend on the value in the record under update.

Instead, use

update EW_POLYLINE
set stan_zmiany = 3
where EW_POLYLINE.STAN_ZMIANY = 0
and NOT EXISTS (
    SELECT 1
    FROM EW_OBIEKTY 
    INNER JOIN EW_OB_ELEMENTY 
        ON EW_OBIEKTY.UID = EW_OB_ELEMENTY.UIDO
    WHERE EW_OBIEKTY.STATUS = 0 AND EW_OB_ELEMENTY.TYP <> 1
    AND EW_OB_ELEMENTY.IDE = EW_POLYLINE.ID
)

Notice the use of not exists instead of exists, because you actually want to update the records from EW_POLYLINE that do not fulfill that requirement.

This way you don't need the left join in the sub-query, and the condition EW_POLYLINE.ID = EW_OB_ELEMENTY.IDE makes the sub-query correlated to the outer update statement.

Also note that this has a similar form as the select statement in the last solution I provided in my answer to your previous question.



来源:https://stackoverflow.com/questions/51318913/updating-selected-rows-in-firebird

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