0

I've got a query that executes just fine until I try to insert the results into a new table. After searching all over and changing things here and there that don't really make much of a difference from my original query, I'm hoping someone here can figure out what's going on.

INSERT INTO new_table(col1, col2, col3, col4)
SELECT t1.col1, t2.col2, t1.col3, t1.col4
FROM table1 t1 LEFT JOIN table2 t2 ON (t1.col1=t2.col1)
WHERE (t2.col1 IS NOT NULL)

When I run this query, the new table is filled as if I had just said INSERT INTO new_table SELECT * FROM table1, which obviously cuts out any of the matched values from table2. As I said, running this query without the INSERT statement returns accurate results. Any ideas?

4
  • 1
    why are you doing a left join on col1 and then making the WHERE be t2.col1 IS NOT NULL? That generates the same set as a regular join.
    – dnagirl
    Commented Feb 28, 2013 at 18:30
  • @Sebas This is embarrassing, but yeah, that was the problem. Thanks for making me look at that. Could have sworn they were the same.
    – Tim
    Commented Feb 28, 2013 at 18:34
  • @dnagirl I check if t2.col1 is not null to exclude any records where there isn't a match between t1.col and t2.col
    – Tim
    Commented Feb 28, 2013 at 18:35
  • @dnagirl Thanks for pointing out that it pulls in the same thing as a regular join - that didn't occur to me.
    – Tim
    Commented Feb 28, 2013 at 18:40

1 Answer 1

3

why not just

CREATE TABLE new_Table as SELECT t1.col1, t2.col2, t1.col3, t1.col4
FROM table1 t1 LEFT JOIN table2 t2 ON (t1.col1=t2.col1)
WHERE (t2.col1 IS NOT NULL)

your indexes won't be there, but this looks like a summary table based on the left join...

1
  • Didn't know a table could be created this way. I didn't have indexes, so no problem on that front. This retains the column types that match and changes the ones that didn't match to comply with the new data. Since that solves the problem that Sebas pointed out in their comment above and also taught me something new, you get accepted. Thank you for the help!
    – Tim
    Commented Feb 28, 2013 at 18:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.