数据库
首页 > 数据库> > mysql – sql insert to table realted到另一个表和常量值

mysql – sql insert to table realted到另一个表和常量值

作者:互联网

我有2个SQL表,table1和table2.

table1有两列,我想向这些列插入值.
其中一列应获取静态值,另一列应获取一个值,该值是来自table2的查询的结果.

如果我想单独插入静态数据,我会这样做:

INSERT INTO table1(login_id)
VALUES ('1234');

如果我想单独插入动态值,我会这样做:

INSERT INTO table1(user_uuid)
SELECT users_uuid FROM table2 where first_name like 'ortal';

如何在一个动作中将两个值都插入到table1中?

如果我尝试第一个查询,我得到:

11:20:45    INSERT INTO table1(login_id ,user_uuid) VALUES ('1234') Error Code: 1136. Column count doesn't match value count at row 1   0.000 sec

INSERT INTO `users`.`table1` (`login_id`) VALUES ('1234');

ERROR 1364: 1364: Field 'user_uuid' doesn't have a default value

解决方法:

您可以将常量添加到选择列表中,并将它们视为列:

INSERT INTO table1(user_uuid, login_id)
SELECT users_uuid, '1234' FROM table2 WHERE first_name LIKE 'ortal';

标签:mysql,sql,sql-server,sql-insert
来源: https://codeday.me/bug/20190608/1200132.html