Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into one column by selecting another column in other table but how fill the second column

i have a table which has two columns i'd fill one of the columns by selecting other table column data but how can i fill the next column cause i can't use VALUE. Here's the code

INSERT INTO Numbers(number, val) SELECT LaptopID FROM Laptop WHERE Laptop.Pid = 2 

as you can see the "val" column left empty how can i fill that?

like image 990
shervin - Avatar asked Aug 07 '12 15:08

shervin -


People also ask

How do you use data from certain columns of an existing table to populate a new table with a matching structure?

How do you use data from certain columns of an existing table to populate a new table with a matching structure? Place a SELECT command within an INSERT command. When would you usually specify primary key constraints? You add a primary key in the CREATE TABLE command.

How can I insert values from one column to another table in SQL?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.

How do I insert two columns from another table in SQL?

Overview of SQL ADD COLUMN clauseFirst, specify the table to which you want to add the new column. Second, specify the column definition after the ADD COLUMN clause.


2 Answers

Use NULL if the column allows it:

INSERT INTO Numbers(number, val)
SELECT LaptopID, NULL
FROM Laptop WHERE Laptop.Pid = 2

Or use the intended (hardcoded) value that you want.

If number:

INSERT INTO Numbers(number, val)
SELECT LaptopID, 2
FROM Laptop WHERE Laptop.Pid = 2

or if text:

INSERT INTO Numbers(number, val)
SELECT LaptopID, 'val'
FROM Laptop WHERE Laptop.Pid = 2
like image 191
aF. Avatar answered Sep 23 '22 21:09

aF.


If you don't have a corresponding value that needs to go into number; then you can just put zero or NULL:

Somethign like this---

INSERT INTO numbers (number, val)
SELECT NULL, laptopid
  FROM laptop
 WHERE laptop.pid = 2
like image 24
Roberto Navarro Avatar answered Sep 21 '22 21:09

Roberto Navarro