0

I'm trying to insert into a relational table with the result of two SELECT queries.

table 1:

id | url
-------------------------
1  | http://something.com

table 2:

id | address
----------------------------
1  | [email protected]

table 3:

table1_id | table2_id
---------------------
1         | 1

And I'm trying to build a INSERT query combined out of two SELECTs and a UNION

I've been working with this:

INSERT INTO table3
SELECT id FROM table1
WHERE table1.url = 'http://something.com'
UNION
SELECT id FROM table2
WHERE table2.address = '[email protected]';

Where have I gone wrong with this? I'm getting an error on the second SELECT, it is able to SELECT the first ID and pass it into the INSERT, but it's trying to insert (1, null) even though the second SELECT is valid on its own.

4
  • When it failed, what is the exact error message? Commented Nov 18, 2015 at 21:50
  • UNION ALL keeps duplicates, but that's not the answer. You need a CROSS JOIN. Commented Nov 18, 2015 at 21:50
  • "insert into a relational table" - all tables in a relational database are "relational". Commented Nov 18, 2015 at 21:51
  • I dont get the logick using union in this case , join or 2 subqueries is what you needed Commented Nov 18, 2015 at 22:06

1 Answer 1

1
INSERT INTO table 3
    select A.id, B.id
    from Table1 A 
    cross join Table2 B
    where A.url = 'http://something.com'
      and B.address = '[email protected]'
Sign up to request clarification or add additional context in comments.

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.