如何将数据从表复制到另一个
如何将数据从表复制到另一个如何将数据从表复制到另一个
插入所有的指导员(除了具有与学生相同的ID)与tot_creds = 0学生表,在同一部门
现在删除上述所有新增加的“学生”(注:谁拥有tot_creds = 0不应该被删除已有的学生)
导师表:
ID Name dept_name salary
10101 Srinivasan Comp. Sci. 65000.00
12121 Wu Finance 90000.00
15151 Mozart Music 40000.00
22222 Einstein Physics 95000.00
32343 El Said History 60000.00
33456 Gold Physics 87000.00
45565 Katz Comp. Sci. 75000.00
58583 Califieri History 62000.00
76543 Singh Finance 80000.00
学生:
ID Name dept_name tot_cred
00128 Zhang Comp. Sci. 102
12345 Shankar Comp. Sci. 32
19991 Brandt History 80
23121 Chavez Finance 110
44553 Peltier Physics 56
45678 Levy Physics 46
70557 Snow Physics 0
我已经试过这种插入,但什么也没有发生影响好心0行引导我
insert into student select ID, name, dept_name, 0
from instructor
where ID != instructor.ID
我想你想要这样的:
INSERT INTO student (id, name, dept_name, tot_cred)
SELECT instructor.ID, instructor.name, instructor.dept_name, 0
FROM instructor LEFT JOIN student on instructor.ID = student.ID
WHERE student.ID IS NULL
AND instructor.tot_cred <> 0
这将插入教师机智h非零总学分与现有学生不匹配。你的#2有点神秘,所以我正在猜测你打算用那部分。
我会使用not exists
子句来过滤现有的记录。
insert into Student (ID, name, dept_name, tot_cred)
select ID, name, dept_name, 0
from Instructor
where not exists (
select 1
from Student
where ID = Instructor.ID
)
然后从Instructors表中删除它们(如果我理解了第2部分的话)。
delete
from Instructor
where exists (
select 1
from Student
where ID = Instructor.ID
)
尽管假设ID在Student和Instructor表格之间是全局唯一的。
此代码的作品,但我想要删除我们最近插入的学生表中的数据。 – Faraz
那么,如果你只是立即删除它们,为什么还要插入它们呢?但是,如果是这样,您可能需要查看['output'子句](https://msdn.microsoft.com/en-us/library/ms177564.aspx)。 – beercodebeer
实际上,我正在为我的数据库实践做这个工作。 – Faraz
INSERT INTO Students
(ID, Name, dept_name, salary)
SELECT
I.ID, I.Name, I.dept_name, I.salary
FROM
Instructors I
LEFT JOIN
Students S ON S.ID = I.ID
WHERE
S.ID IS NULL
AND S.tot_cred <> 0
DELETE FROM Instructors WHERE ID IN (SELECT ID FROM STUDENT)
您可以用下面的办法,以便从一个表中的数据复制到另一个表:
--Insert data from one table to another table (same or different dBs)
INSERT INTO DestinationDB.dbo.DestinationTable(ColumnX, ColumnY, ColumnZ, ColumnW, ColumnT)
--If the ID column of the DestinationTable is automatically created (isIdentity) do not insert value to the ID column.
SELECT ColumnA, ColumnB, ColumnC, 'Test', 1
FROM SourceDB.dbo.SourceTable
WHERE < Search Conditions >
希望这有助于...
绝不会有此查询任何行。这是不可能的ID值不等于ID。你需要为这种类型的事物使用左连接。 –
这是MySQL还是Microsoft SQL Server? – tadman
我想要在mysql和sql中 – Faraz