简体   繁体   English

SQL查询...我需要从表1的同一列中插入2个值到表2的2个不同列中

[英]SQL query…I need to insert 2 values from same column of table1 to 2 different columns of table2

insert into friends (user_id1,user_id2) select user_id from user where UserName='summer'or UserName='winter' This gives an error. insert into friends (user_id1,user_id2) select user_id from user where UserName='summer'or UserName='winter'这将导致错误。 I want to insert user_id of 'summer' into user_id1 and user_id of 'winter' into user_id2. 我想将'summer'的user_id插入到user_id1中,并将'winter'的user_id插入到user_id2中。 Please help? 请帮忙?

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

Select must have same number of columns as insert, therefore: Select必须具有与插入相同的列数,因此:

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

Should do the trick 应该做的把戏

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 SQL字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mysql需要从table1中获取一列两次,然后通过table2的两个不同列对它们进行排序 - Mysql need to get one column two times from table1 and sort them by two different columns of table2 将表1中的多个列合并到表2中的一列 - merging multiple Columns from table1 into one column in table2 我需要从表 1 中搜索学生和表 2 中的老师 - I need to search Student from Table1 and Teacher in Table2 SQL查询,按表2行从表1中选择 - SQL query, select from table1 order by table2 rows 从table1插入或替换到table2 - insert or replace into table2 from table1 如何将数据从表1插入表2? - How do I insert data from table1 to table2? SQL:我想从table1中选择所有列,其中table1中的columnA等于table2中的ColumnB - SQL: I want to select all columns from table1 where columnA in table1 is equal to ColumnB in table2 我正在尝试将数据从table1填充到table2。我的sql查询是否正确? - I am trying to populate data from table1 to table2 .Is my sql query correct? 新表中有两列(table1 join table2),它们具有相同的列名,如何分别获取两者的值 - There are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively SELECT *(table1),列名(table2)FROM table1 JOIN table2 - SELECT *(table1), column name (table2) FROM table1 JOIN table2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM