SQL查询...我需要将table1的同一列中的2个值插入到table2的2个不同列中

时间:2014-02-25 12:45:10

标签: mysql sql

insert into friends (user_id1,user_id2) select user_id from user where UserName='summer'or UserName='winter' 这给出了一个错误。我想将'summer'的user_id插入user_id1,将'winter'的user_id插入user_id2。请帮帮忙?

3 个答案:

答案 0 :(得分:0)

insert into friends (user_id1,user_id2) 
select user_id, -1 from user where UserName='summer'

update friends 
set user_id2 = (select user_id from user where UserName='winter')
where user_id2 = -1

答案 1 :(得分:0)

Select必须具有与insert相同的列数,因此:

INSERT INTO friends (user_id1,user_id2)
SELECT (SELECT user_id FROM user where UserName='Summer') AS user_id1, (SELECT user_id FROM user WHERE UserName='Winter') AS user_id2

应该做的伎俩

答案 2 :(得分:0)

INSERT INTO table2 (user_id1,user_id2)
SELECT
  (SELECT UserName
   FROM table1
   WHERE UserName='Summer') AS user_id1,

  (SELECT UserName
   FROM table1
   WHERE UserName='Winter') AS user_id2

SQL FIDDLE