Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Insert Into with Inner Join

I want to make my insert query which has an inner join to the Users table.

The example of the tables is like this:

Users:

id | fullName | preferredName | email              | mobile   | password
1  | Pan Lim  |  Lim          | [email protected] | 64557812 | passone
2  | Gong My  |  Gong         | [email protected]   | 61345671 | passtwo

Orders:

id | userid(Foreign key of "id" from Users | timestamp
1  |               1                       | 2016-06-10 11:45:31

I'm trying to insert into Orders relating to only knowing the userid from the Users table. It show like this:

Orders:

id | userid(Foreign key of "id" from Users | timestamp
1  |               1                       | 2016-06-10 11:45:31
2  |               2                       | 2016-08-14 12:45:31

But when I test on my SQL query, it has error on this query.

INSERT INTO Orders (id, userid, timestamp) 
SELECT Orders.id, Orders.userid, Orders.timestamp FROM Users INNER JOIN Orders ON  Orders.id = Users.id
like image 623
Lue Fang Avatar asked Jun 10 '17 04:06

Lue Fang


People also ask

Can we use insert with join in SQL?

SQL server insert multiple rows using an inner join would be possible. -- Insert into line will select the columns.

Can inner join add rows?

Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have matching values in two or more tables. This join is based on a logical relationship (or a common field) between the tables and is used to retrieve data that appears in both tables.

How do I use between inner joins in SQL?

The BETWEEN operator is a logical operator that allows you to specify whether a value is in a range or not. To run this SQL statement, Press the Execute Query button. By doing this, it shows the records of the price range between 90 and 100 as a result.


2 Answers

If your id is not auto increment in Orders table.

INSERT INTO orders ( id,userid, timestamp) 
SELECT o.userid , o.timestamp FROM users u INNER JOIN orders o ON  o.userid = u.id

If your id is auto increment in Orders table.

INSERT INTO orders ( userid, timestamp) 
SELECT o.userid , o.timestamp FROM users u INNER JOIN orders o ON  o.userid = u.id
like image 156
VNT Avatar answered Oct 29 '22 23:10

VNT


If Orders.Id is unique your SQL query will fail. You are trying to insert one or more existing records into the Orders table so it will be duplicates of Id.. I'm not sure what you are trying to achieve, but this should work:

INSERT INTO Orders ( userid, timestamp) 
SELECT Orders.userid, Orders.timestamp FROM Users INNER JOIN Orders ON  Orders.id = Users.id

Edit: Orders.Id should be an unique id for the record in orders and Users.Id should be an unique id for the record in the user table? in this case you cannot join on these two.

like image 21
Mr Zach Avatar answered Oct 30 '22 00:10

Mr Zach