1

I have done my research but can not figure out how to do this. It is super simple to insert from another table but I want to include WHERE statements.

I want to insert value of a single column, column_Q from table A into table B's column_Q WHERE table A's column_W = '100' and column_Q does not already exist in table B.

I tried:

INSERT INTO B (column_Q) select DISTINCT(column_Q) 
from A WHERE column_W = 100 AND b.column_Q<>a.column_Q;

Where am I doing wrong?

PS. Both tables already contain values. No field is Null.

2 Answers 2

4
INSERT
INTO    b (q)
SELECT  DISTINCT q
FROM    a
WHERE   a.w = 100
        AND a.q NOT IN
        (
        SELECT  q
        FROM    b
        )

If your b.q has a UNIQUE constraint defined on it, then just use:

INSERT
IGNORE
INTO    b (q)
SELECT  q
FROM    a
WHERE   w = 100
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot refer to the left side of the "assignment", because there is no current row from B to compare to (that would be the one you are inserting) You need to check if a similar row is already present in B, like in:

INSERT INTO B (column_Q)
SELECT DISTINCT(A.column_Q) 
FROM A 
WHERE A.column_W = 100
AND NOT EXISTS (
    SELECT *
    FROM B
    WHERE B.column_Q = A.column_Q
    );

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.