【问题标题】:Update table with value from the same table using a sub query使用子查询使用同一表中的值更新表
【发布时间】:2018-09-06 21:25:01
【问题描述】:

我使用 sqlite 并且有一个看起来像这样的表:

我正在尝试使用 col2 对应 col1 的值更新引用列

我试过像

这样的查询
update tab1 
set refer = (select col2 from tab1 where col1 = refer) 
where col1 = 2

这但不起作用。

我也试过了

update tab1 
set refer = (select tem1.col2 
             from tab1 tem1, tab1 tem2 
             where tem1.col1 = tem2.refer and tem2.col1=2) 
where col1 = 2

这行得通。

但我不确定这是否是正确的做法。

Expected

【问题讨论】:

  • 您实际使用的是哪些 dbms? (删除未涉及产品的标签。)
  • 这里的大多数人想要格式化文本,而不是图像(或图像链接)。
  • 请发布预期结果
  • 哪个数据库正在使用??

标签: mysql sql sql-server sqlite


【解决方案1】:

查看您的代码似乎您需要

   update tab1 
   set refer = col2  
   when col1 = refer 
   and col1 = 2 

意思是

   update tab1 
   set refer = col2  
   when  refer  2 

如果您正在使用子查询在同一个表上寻找更新,您应该可以使用内部联接

在mysql中

 update tab1 
 INNER JOIN (
      select col1, col2 
      from tab1 
      where col1 = refer ) t t.col1 = tabl1.col1 and  col1 = 2

在 sqllite 中你可以使用

  update tab1 
  set refer = (select t.col2 from (
  select col2 from tab1 where col1 = refer
  ) t )
  where col1 = 2

【讨论】:

  • 抱歉少了一个大括号。它有效,它与我使用的有什么不同,哪个更好?
  • 有效,和我用过的有什么不同,哪个更好?
  • 不同之处在于两个内部子选择强制数据库引擎创建一个临时表,因此更新不适用于同一个..表..哪个更好? ,,mine 更清楚 .. 您使用无用的笛卡尔积来获得相同的结果.. 但是对于大表,您会产生性能问题
  • 相同的查询不适用于where col1=5,它正在更新为 Null,你能帮忙@scaisEdge
  • 我认为它有时不起作用,它正在使用空值进行更新。 @scaisEdge
【解决方案2】:

最后这个查询完美运行:

update tab1 
set refer = (select t1.col2 from tab1 as t1 where t1.col1 = tab1.refer) 
where tab1.col1 = 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多