我有一张名为'学生'列'姓名'和'滚动编号'
name Roll_Number
A 1
A 2
A 1
B 2
B 2
C 3
C 2
D 4
我想删除此表中具有相同名称但不同Roll_number的所有行,并将这些行插入新表格' Temp'。所以操作后两个表应该是这样的
表学生
name Roll_Number
B 2
B 2
D 4
表温度
name Roll_Number
A 1
A 2
A 1
C 3
C 2
因为A和C都有不同的Roll_Number列值,所以我们从Student表中删除A和C的所有条目并将其添加到Temp Table
那么如何通过mysql查询来完成呢?
答案 0 :(得分:1)
尝试类似:
对于学生表:
SELECT name, Roll_Number
FROM Student
GROUP BY name
HAVING COUNT(DISTINCT Roll_Number) = 1
对于临时表:
SELECT name, Roll_Number
FROM Student
GROUP BY name
HAVING COUNT(DISTINCT Roll_Number) > 1
答案 1 :(得分:1)
以下是一个查询,用于插入所有记录,对于给定的name
有多个Roll_Number
,这些记录会添加到新的临时表Temp
中<: / p>
INSERT INTO Temp (name, Roll_Number)
SELECT name, Roll_Number
FROM Student
WHERE name IN (SELECT name
FROM Student
GROUP BY name
HAVING COUNT(DISTINCT Roll_Number) > 1)
这是一个从Student
删除这些相同记录的查询:
DELETE FROM Student
WHERE name IN (SELECT name FROM Temp)
请注意,在从旧表中删除它们之前,我先插入新表(原因很明显)。
答案 2 :(得分:1)
以下是适用于我的查询,该查询是根据SMA
和Tim
个答案创建的。
用于插入临时表
INSERT INTO Temp (name, Roll_Number)
SELECT name, Roll_Number
FROM Student
WHERE name IN (SELECT name
FROM Student
GROUP BY name
HAVING COUNT(DISTINCT Roll_Number) > 1);
删除记录查询与Tim
DELETE FROM Student
WHERE name IN (SELECT name FROM Temp)
感谢他们两人