2016-07-28 41 views
0

我想基于以下查询在MySQL中设置列值。基于连接和自我连接设置列值MySql Rails

select * from table1 t1 
join table2 t2 
on t1.id = u.t1_id 
and t2.status = 'verified' 
and not exists (
    select 1 
    from table2 t2_2 
    where t2.t1_id = t2_2.t1_id 
    and t2_2.updated_at > t2.updated_at 
) 

该查询返回我想要的结果,但是当我尝试

SET t1.column_k = 'some value' 

添加到年底,我收到只是说与你的MySQL版本You've got a syntax error near set t1.column_k....速查手册错误。

我真的很想知道如何在这个查询的结果中包含一个集合,并且在解决这个问题时遇到了麻烦。任何帮助或想法?

对我来说很困难和困惑,我认为是因为self join。最终的计划是将这个带有set命令的查询移到一个migration file in rails,一旦我有了它的工作。

回答

0

您需要一个updateSelect不用于设置值。

update table1 t1 join 
     table2 t2 
     on t1.id = u.t1_id and 
      t2.status = 'verified' and 
      not exists (select 1 
         from table2 t2_2 
         where t2.t1_id = t2_2.t1_id and 
          t2_2.updated_at > t2.updated_at 
        ) 
    set t1.column_k = 'some value';