0

I have a table 'users' with a column of 'ID'. I want to select 2 different 'ID's' based on 2 different parameters and insert them both into another table known as 'jobs'.

INSERT INTO jobs (customer_id, client_id) 
SELECT id, id from users 
WHERE username = ? 
AND username = ?

Basically I want to get the ID of two different people and insert them both into the new table.

I would then bind the parameters to ?, and they would look something like 'john' and 'steve'. I have tried the code above but I know it is the wrong syntax. Any ideas would be greatly appreciated. Thanks

2 Answers 2

2

You could use a self-join:

INSERT INTO jobs
  (customer_id, client_id)
SELECT customer.id, client.id
FROM   users customer
  JOIN users client ON customer.username = ? AND client.username = ?

Or, you could use subqueries:

INSERT INTO jobs
  (customer_id, client_id)
VALUES (
  (SELECT id FROM users WHERE username = ?),
  (SELECT id FROM users WHERE username = ?)
)
Sign up to request clarification or add additional context in comments.

1 Comment

I never thought of joining a table to itself, thank you for the accurate and very quick response!
0

Well, you could use subquerys

INSERT INTO jobs (customer_id, client_id) 
VALUES ( 
         (SELECT field from table where id = 2), 
         (SELECT field from table2 where id = 12) 
 )

I'm not pretty sure about the sintax, since I haven't tested, but I'm guessing it could solve it.

I often use such things in WHERE or in the SELECT statement. Just remember to return a single field and a single row in the subquerys.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.