8

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ortal Blumenfeld Lagziel
  • 2,415
  • 3
  • 23
  • 33

1 Answers1

8

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';
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • From the code you've provided you're inserting data into table1? Your issue is that user_uuid appears to be a NOT NULL field which means you have to populate this when inserting other data. The code that @mureinik provided does that for you. If you're talking about inserting data into table2 then you need to correct your original question. – Rich Benner Jun 04 '16 at 08:40