Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SQL组合来自两个或多个其他表的列数据创建表_Sql_Sql Insert_Multiple Tables - Fatal编程技术网

使用SQL组合来自两个或多个其他表的列数据创建表

使用SQL组合来自两个或多个其他表的列数据创建表,sql,sql-insert,multiple-tables,Sql,Sql Insert,Multiple Tables,我试图找出如何使用其他两个表中的列数据将数据插入到新的联接表中。这一点起初看起来很简单,但现在已经不明显了——我能在任何地方找到解决方案吗 例如: 我有tProfiles表: 从tProfiles中选择prof_id prof_id 1 2 3 4 5 ... 和包含角色tRole的表 从tRole中选择roleid roleid 1 2 3 4 5 6 7 ... 新的tRoleByProfile需要tRole的所有角色和Tprofile的所有prof_id,使用如下插入: 插入到tRo

我试图找出如何使用其他两个表中的列数据将数据插入到新的联接表中。这一点起初看起来很简单,但现在已经不明显了——我能在任何地方找到解决方案吗

例如: 我有tProfiles表:

从tProfiles中选择prof_id

prof_id

1
2
3
4
5
...
和包含角色tRole的表

从tRole中选择roleid

roleid
1
2
3
4
5
6
7
...
新的tRoleByProfile需要tRole的所有角色和Tprofile的所有prof_id,使用如下插入:
插入到tRoleByProfile(RoleId,ProfileId)

现在我在这里做了几次连接,以获得其中有活动用户的配置文件,如下所示

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'
注意,在select中,我必须在完全联接上使用distinct。如果不使用Distinct,将创建大量重复数据。有关完全联接的详细信息,请参阅


现在,我的新联接表具有合并的两个表所需的精确数据

你本可以

INSERT INTO tRoleByProfile 
   SELECT r.RoleId, p.prof_id 
   FROM tRole r
   JOIN tProfiles p;
不带任何条件地连接两个表将生成一个结果集,该结果集包含两个表中记录的每个组合。换句话说,每个配置文件都将接收每个角色

要过滤笛卡尔连接中包含的行(即没有关系的连接),请通过将它们作为单独的选择来过滤上面连接的任一侧,如

INSERT INTO tRoleByProfile 
SELECT r.RoleId, p.prof_id 
FROM tRole r
JOIN (SELECT prof_id 
      FROM tProfiles 
      WHERE blah...)

Rodney我的查询不包括所有组合,只要我添加了distinct。。。见下文。我测试过这个。。。没有distinct,我得到了所有可能的行,但是使用distinct,我得到了完全唯一的结果,它按照我的预期工作。。。也就是说,在重读你的评论后,不插入重复的内容等会误解你的答案。您的解决方案看起来不错,感谢您的解决方案。不知道为什么我会被否决。虽然这似乎是一个简单问题的简单解决方案,但我在interweb和stackoverflow上搜索了很长一段时间,遗憾的是没有找到答案。因此这篇文章。我证明了这是有效的,并且避免了重复。。。无论如何。