来自其他表的更新表的sql与每个表都有条件,不起作用

时间:2019-04-16 05:46:30

标签: sql db2 sql-update db2-400

首先,我不太熟悉DB2 SQL。

我有一个TABLE和TABLEB。一个TABLE包含最后的修改数据,而TABLE B包含来自表TABLE A的数据历史记录/记录。

我想更新填充有 TABLEB.LAST_PRICE 的列 TABLEA.LAST_PRICE (条件为DEAL_DATE ='1753-01-01'和CODE <>'')(条件为DEAL_DATE <>'1753-01-01'和CODE <>''并按CHANGE_DATE desc限制排序1),其中两个表的外键为TABLEA.ID = TABLEB.ID

我尝试使用以下3条SQL更新TABLEA,但没有成功:

 1. update DB.TABLEA as a set a.LAST_PRICE = (select LAST_PRICE from
    DB.TABLEB as b where b.DEAL_DATE <> '1753-01-01' and a.ID = b.ID and
    b.CODE <> '' order by b.CHANGE_DATE desc FETCH FIRST 1 ROWS ONLY)
    where a.DEAL_DATE = '1753-01-01' and a.CODE <>  '' ;




2.  update DB.TABLEA as a set a.LAST_PRICE = (select LAST_PRICE from
    DB.TABLEB as b where b.DEAL_DATE <> '1753-01-01' and a.ID = b.ID and
    b.CODE <> '' order by b.CHANGE_DATE desc limit 1) where a.DEAL_DATE = '1753-01-01' and a.CODE <>  '' ;




3. update DB.TABLEA set a.LAST_PRICE = b.LAST_PRICE from DB.TABLEA  a
    join DB.TABLEB  b on a.ID = b.ID where a.DEAL_DATE = '1753-01-01'
    and a.CODE <> '' and b.DEAL_DATE <> '1753-01-01' and b.CODE <> ''
    order by b.CHANGE_DATE desc FETCH FIRST 1 ROWS ONLY;

这个查询让我发疯了。 谢谢您的所有帮助。

1 个答案:

答案 0 :(得分:0)

您的日期似乎转换不正确。优化程序可能会将您的TABLEB DEAL_DATE转换为时间戳,然后转换为与纯字符串不匹配的字符。比较日期时,通常最好将它们作为实际日期进行比较,而不仅仅是它们的表示形式。

update DB.TABLEA as a set a.LAST_PRICE = (select LAST_PRICE from
    DB.TABLEB as b where cast(b.DEAL_DATE as date) <> cast('1753-01-01' as date) and a.ID = b.ID and
    b.CODE <> '' order by b.CHANGE_DATE desc FETCH FIRST 1 ROWS ONLY)
    where cast(a.DEAL_DATE as date) = cast('1753-01-01' as date) and a.CODE <>  '' ;