我想在交换数据用例的时候

时间:2016-03-03 05:40:44

标签: mysql

table test data

 UPDATE tb_test 
    set name =  
    ( CASE  
    WHEN (id = 1) THEN (select DISTINCT name from tb_test where id = 2) 
    WHEN (

id = 2) THEN (select DISTINCT name from tb_test where id = 1) 
END )

结果:

[SQL] UPDATE tb_test

set name =  
( CASE  
WHEN (id = 1) THEN (select DISTINCT name from tb_test where id = 2) 
WHEN (id = 2) THEN (select DISTINCT name from tb_test where id = 1) 
END )

[Err] 1093 - You can't specify target table 'tb_test' for update in FROM clause

2 个答案:

答案 0 :(得分:0)

在同一个表格中,您无法同时执行selectupdate操作

 UPDATE tb_test 
 set name =  
 (CASE  
    WHEN id = 1 THEN (select sub_query1.new_name from (select DISTINCT name as new_name from tb_test where id = 2 limit 1) as sub_query1 )   
    WHEN id = 2 THEN (select sub_query2.new_name from (select DISTINCT name as new_name from tb_test where id = 1 limit 1) as sub_query2) 
END);

答案 1 :(得分:0)

它适合你

  UPDATE tb_test
  set name =
    ( 
    CASE
         WHEN id = 1
         THEN (select * from (select DISTINCT name from tb_test where id = 2)t)
         WHEN id = 2
         THEN (select * from (select DISTINCT name from tb_test where id = 1)y) 
    END 
   );