Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql insert to table realted to another table and constant values

I have 2 SQL tables, table1 and table2.

table1 has two columns and I want to insert values to these columns. one of the columns should get a static value and the other column should get a value that is a result of a query from table2.

If I wanted to insert the static data separately I would do:

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

and if I wanted to insert the dynamic value separately I would do:

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

How can insert both values to table1 in one action?

If I try the first query I get:

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
like image 653
Ortal Blumenfeld Lagziel Avatar asked Jun 04 '16 08:06

Ortal Blumenfeld Lagziel


1 Answers

You can add the constants to your select list and treat them a columns:

INSERT INTO table1(user_uuid, login_id)
SELECT users_uuid, '1234' FROM table2 WHERE first_name LIKE 'ortal';
like image 188
Mureinik Avatar answered Sep 21 '22 05:09

Mureinik