SQL: Copying data from 1 table to 3 others
I've been reading W3 Schools on SQL Insert INTO, which from my understanding creates a backup copy of data into a new table. I have over 300 records to add.
I have 4 tables, one of which is the source I am coping from. 1) Card Access, which is the source 2) pro_Profile, main dest 3) pro_Email, secondary dest 4) pro_Address, third dest
I have no control over this database schemea. It's too much work to rebuilt everything to work with 1 table then the three. Also the data I am adding maybe a duplicate of what exists, so we need to skip those too.
Card access has these fields: CSUID which maps to pro_Profile firstName which maps to pro_Profile lastName which maps to pro_Profile eName which maps to pro_Profile Email Address which maps to pro_Email Contact Phone Number which maps to pro_Address
Once I copy into Pro_Profile it'll need to get the primary key, profileID which is the reference to the profile accross all these tables.
How do I copy all this data first into the pro_Profile so I can get the unique key profileID which is a forgien key to all the other tables?
Here's my code so far:
SELECT
FirstName,
LastName,
eName,
CSUID
INTO
WHERE NOT EXISTS (
Select
firstName,
LastName
From
pro_Profile
)
New QUERY which affects 0 rows
INSERT INTO pro_Profile ("firstName","lastName","userName","depa开发者_StackOverflow中文版rtmentID","csuID")
SELECT "First Name","Last Name","eName","Department","CSUID"
FROM "Card Access"
WHERE NOT EXISTS (
Select
firstName,
LastName
From
pro_Profile
)
The format for your insert will be
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
So basically you select what you want to insert. You will be able to do it as one statement from all the tables and can add a where clause also. Check out the answers to this question also.
UPDATE: First write your sql query to get the rows you want to insert. So the query you have above:
SELECT "First Name","Last Name","eName","Department","CSUID"
FROM "Card Access"
WHERE NOT EXISTS (
Select
firstName,
LastName
From
pro_Profile
)
when ran alone should return all the results you will be inserting. What do you get when you just run that?
UPDATE: I think you are misunderstading not exist. Check out this. I think you need something like:
SELECT "First Name","Last Name","eName","Department","CSUID"
FROM "Card Access" ca
WHERE (
Select count(*)
From pro_Profile
WHERE firstName = ca.firstName
AND LastName = ca.lastName
) = 0
UPDATE: Or alternatively you should be able to do:
SELECT "First Name","Last Name","eName","Department","CSUID"
FROM "Card Access" ca
WHERE NOT EXISTS (
Select
firstName,
LastName
From
pro_Profile
WHERE firstName = ca.firstName
AND LastName = ca.lastName
)
精彩评论