SQL - 使用基于两个 table 的表达式更新 table 列值

SQL - Update table column values using expression based on two tables

使用 Sqlite 数据库,我有一个用户 table 和一个具有以下列的排名 table:

用户table: 编号 |排名 | xp

排名table 编号 |姓名 | xpLowerLevel

我的目标是根据排名 table 中的 xpLowerLevel 字段更新所有用户行的 rankId 字段。我的Sql表达式如下:

UPDATE users 
SET rankId = (SELECT id FROM ranks 
              WHERE xpLowerLevel <= users.xp  
              ORDER BY ABS(xpLowerLevel - users.xp) 
              LIMIT 1);

这给了我以下错误 没有这样的列:users.xp。我做错了什么?

问题是 order by 子句,显然 SQLite 不接受对正在更新的 table 的引用。但我不确定您是否需要该参考资料。您的专栏名为 xpLowerLevel,这让我觉得您实际上想要:

update users
set rankid = (
    select id 
    from ranks
    where xpLowerLevel <= users.xp  
    order by xpLowerLevel desc
    limit 1
);

具有FIRST_VALUE()window功能:

UPDATE users 
SET rankId = (
  SELECT DISTINCT FIRST_VALUE(id) OVER (ORDER BY ABS(xpLowerLevel - users.xp))
  FROM ranks 
  WHERE xpLowerLevel <= users.xp  
);

或者因为已经有条件:

WHERE xpLowerLevel <= users.xp

区别:

users.xp - xpLowerLevel

>= 0
所以不需要函数 ABS():

UPDATE users 
SET rankId = (
  SELECT DISTINCT FIRST_VALUE(id) OVER (ORDER BY users.xp - xpLowerLevel)
  FROM ranks 
  WHERE xpLowerLevel <= users.xp  
);