我试图弄清楚如何使用来自其他两个表的列数据将数据插入到新的连接表中。这似乎起初很简单,但现在我不能立即明白这个解决方案。
实施例: 我有tProfiles表:
从tProfiles中选择prof_id
prof_id
1
2
3
4
5
...
和包含角色的表格tRole
从tRole中选择roleid
roleid
1
2
3
4
5
6
7
...
并且新的tRoleByProfile需要来自tRole的所有角色以及来自tProfiles的所有prof_id,使用如下插入: 插入到tRoleByProfile(RoleId,ProfileId)
答案 0 :(得分:0)
现在我在这里进行多次加入,以便像这样只获得活跃用户的个人资料。
insert into tRoleByProfile(RoleId, ProfileId)
select distinct r.RoleId, p.prof_id from tRole r, tProfiles p
inner join tUserRoles ur on p.PROF_ID = ur.prof_id
inner join tUsers u on u.user_id = ur.user_id
inner join tUserLogins ul on ul.user_id = u.user_id
where u.user_inactive_flg = 'N'
选择中的注意事项我必须在完全加入时使用distinct。不使用Distinct会创建大量重复数据。有关完全加入的详情,请参阅http://www.informit.com/articles/article.aspx?p=30875&seqNum=5。
现在,我的新连接表具有组合两个表所需的确切数据。
答案 1 :(得分:0)
你可能已经完成了......
INSERT INTO tRoleByProfile
SELECT r.RoleId, p.prof_id
FROM tRole r
JOIN tProfiles p;
在没有任何条件的情况下连接两个表将产生一个结果集,该结果集包含来自两个表的记录的每个组合。换句话说,每个配置文件都会收到每个角色。
要过滤笛卡尔连接中包含的行(即没有关系的连接),请通过使它们成为单独的选择来过滤上面JOIN的任一侧,如...
INSERT INTO tRoleByProfile
SELECT r.RoleId, p.prof_id
FROM tRole r
JOIN (SELECT prof_id
FROM tProfiles
WHERE blah...)