简体   繁体   中英

SQL Select insert with Condition (between these two tables)

I am new to Sql. And I have two tables which

table_A (student_id, last_name, email, schoolA, ...)

table_B (student_id, last_name, email, schoolB, ...)

And in table_A, some student_id was Null or ''(empty).

select the student_id from table_B insert into table_A's student_id colm

when only match last_name and email, also when A.student_id is Null or Empty.

here was what I thought

INSERT INTO table_A (student_id) 
SELECT student_id 
    From table_B 
    WHERE table_A.last_name = table_B.last_name AND table_A.email = table_B.email 
        AND table_A.student_id ='' OR table_A.student_id = NULL

I know the sql which I wrote is not make any sense. And I just want to get a simple example or some idea.

Thank your!

This sounds more like an UPDATE statement, rather than an INSERT .

UPDATE A
SET A.student_id = B.student_id
FROM table_A A
INNER JOIN table_B B
  ON A.last_name = B.last_name 
  AND A.email = B.email
WHERE (A.student_id ='' OR A.student_id IS NULL)

Notice you compare student_id to IS NULL , not = NULL . Parentheses are important as well.

Anyway try this:

INSERT INTO table_A (STUDENT_ID)
SELECT B.student_id 
    From table_B AS B, TABLE_A AS A
    WHERE (A.last_name = B.last_name AND A.email = B.email )
        OR A.STUDENT_ID ='' OR A.STUDENT_ID IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM