从两个不同的表MySQL加入所有行

时间:2013-02-06 18:08:16

标签: mysql join union

我一直在尝试加入两个不同表格中的所有行。我尝试过UNION和LEFT JOIN。

现在我刚刚使用了两个单独的查询,并且在另一个之后有一个显示。我想合并两个查询同时显示。

表1称为“批准”,表2称为“评论”。

  

批准
    - id
    - postID
    - postUserID
    - userID

     

评论
    - id
    - postID
    - postUserID
    - 用户ID
    - 评论
    - 日期

3 个答案:

答案 0 :(得分:3)

这里是一个UNION的例子

select id, postID, postUserID, userID, comment, date from comments
union
select id, postID, postUserID, userID, null, null from approves 

答案 1 :(得分:0)

您可以插入正在使用的SQL吗? Union将组合两个表,连接将依次从表中获取所有行并组合所有关联的行。 JOIN默认为内部联接。 UNION实际上将两个表的结果结合起来。如果您希望所有行都能得到a,而b表中的相应注释则使用左连接。

答案 2 :(得分:0)

根据您的表格,您似乎可以JOIN表格:

select *
from approves a
inner join comments c
    on a.userid = c.userid
    and a.postid = c.postid

我猜你需要根据postiduserid加入多列上的表格。

我使用了INNER JOIN,它将返回两个表之间的所有匹配行。如果您只想返回approves表中的那些记录,那么您可以使用LEFT JOIN。如果您需要帮助学习联接语法,这里有一个很棒的visual explanation of joins

您可以使用UNION,但必须为每个表选择所需的列,因为UNION的每个查询中的列数必须相等。所以UNION将是:

select id, postid, postUserId, userId, null as comment, null as date, 'approves' as Src
from approves 
union all
select id, postid, postUserId, userId, comment, date, 'comments' as src
from comments 

请注意,我添加了一个名为src的添加列,可用于确定数据来自哪个表。

相关问题