UNION of 2选择INSERT?

时间:2014-09-20 01:39:13

标签: sql oracle

假设您有一个非关系表Persons,其中包含格式错误的数据:

人:

id       name       city        state      country
('1', 'username1', 'Cityville', 'Alabama', 'USA')
('1', 'username1', 'Cityville', 'Alabama', 'USA')
('2', 'username2', 'Cityville', 'Alabama', 'USA')
('2', 'username2', 'Cityville', 'Alabama', 'USA')
('3', 'username3', 'Knoxville', 'Tennessee', 'USA')

并且您有一个表格设置,将位置ID与城市州国家元组相关联:

位置:

loc_id    city        state    country
 (1,     'Cityville', 'Alabama', 'USA')
 (2,     'Knoxville', 'Tennessee', 'USA')

并且您希望将此数据插入到Clean_Persons中,其中第一行的Clean_Pers是Persons.id,第二行是从位置查找城市州的国家/地区的结果

Clean_Persons

user_id    loc_id
(1,        1)
(2,        1)
(3,        2)

我的尝试:

INSERT INTO Clean_Persons (user_ID, Loc_ID)
SELECT TO_NUMBER(USER_ID) FROM Persons
UNION
SELECT loc_ID FROM Location L JOIN Persons P ON (
   L.city = P.city AND
   L.state = P.state AND
   L.country = P.country 
);

3 个答案:

答案 0 :(得分:0)

我认为你不需要在这里做一个UNION ALL我觉得它应该是这样的......

INSERT INTO Clean_Persons (user_ID, Loc_ID)
SELECT DISTINCT TO_NUMBER(P.USER_ID),   L.loc_ID 
FROM Location L JOIN Persons P 
ON (
   L.city = P.city AND
   L.state = P.state AND
   L.country = P.country 
);

答案 1 :(得分:0)

您不需要UNION,而只需JOIN

INSERT INTO Clean_Persons (Id, Name, Loc_Id)
SELECT DISTINCT TO_NUMBER(P.Id), P.Name, L.Loc_Id
FROM Persons P 
    JOIN Location L ON P.City = L.City 
        AND P.State = L.State 
        AND P.Country = L.Country

鉴于Persons表中的重复数据,我还使用DISTINCT来避免重复。有了这个说,同一个人可能有多个地址吗?如果是,请考虑为PersonLocations添加另一个表,因为此当前查询将在Clean_Persons表中插入重复记录。这有助于保持数据库的标准化。

答案 2 :(得分:0)

您只需使用INNER JOIN而不使用UNION

INSERT INTO Clean_Persons (user_ID, Loc_ID)
SELECT DISTINCT p.id AS user_id, l.loc_id
FROM 
  persons p INNER JOIN locations l ON l.city = p.city AND
                                      l.state = p.state AND
                                      l.country = p.country