加入两个sql表

时间:2017-05-25 23:04:27

标签: mysql sql database

我有两张包含数据的表格:

GroupMembers
Users, GroupID

GroupPosts
GroupID,PostID

我想得到一个包含

的表格输出
Users, GroupID, PostID

用户可以属于多个组,每个组可以有多个帖子。所以我想拥有所有用户和每一篇文章。

所以,如果

GroupMembers:

+-------+---------+
| Users | GroupID |
+-------+---------+
| User1 | Group1  |
+-------+---------+
| User2 | Group1  |
+-------+---------+
| User2 | Group2  |
+-------+---------+
| User3 | Group2  |
+-------+---------+

GroupPosts

+---------+--------+
| GroupID | PostID |
+---------+--------+
| Group1  | Post1  |
+---------+--------+
| Group1  | Post2  |
+---------+--------+
| Group2  | Post1  |
+---------+--------+
| Group2  | Post4  |
+---------+--------+

应该返回包含

的表
+-------+--------+-------+
| User  | Group  | Post  |
+-------+--------+-------+
| User1 | Group1 | Post1 |
+-------+--------+-------+
| User1 | Group1 | Post2 |
+-------+--------+-------+
| User2 | Group1 | Post1 |
+-------+--------+-------+
| User2 | Group1 | Post2 |
+-------+--------+-------+
| User2 | Group2 | Post1 |
+-------+--------+-------+
| User2 | Group2 | Post4 |
+-------+--------+-------+
| User3 | Group2 | Post1 |
+-------+--------+-------+
| User3 | Group2 | Post4 |
+-------+--------+-------+

我希望这有道理吗?

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

您可以使用简单的JOIN查询,例如:

SELECT g.users, g.groupID, gp.postid
FROM GroupMembers g JOIN GroupPosts gp ON g.groupID = gp.groupID;

答案 1 :(得分:0)

人们喜欢使用JOIN语法,你也可能喜欢它,但我发现它等同于“oldschool”语法更具可读性:

select a.Users, a.GroupID, b.PostID 
from GroupMembers a, GroupPosts b where b.GroupID = a.GroupID;

使用JOIN只会涉及JOIN ON b.GroupID = a.GroupID之类的东西,我相信。 :)

答案 2 :(得分:0)

选择m.users,m.groupid,p.groupid,p.postid

来自GroupMembers为m

在m.groupid = p.groupid

上加入GroupPosts作为p

在移动设备上,所以无法回复您的帖子,但我认为就是这样。