如何加入两个mysql表

如何加入两个mysql表

问题描述:

我有两个mysql表。即,如何加入两个mysql表

  1. db_post
  2. db_like

// db_post

id || name || username || unique_key || pub 

1  Jit  jit11   unkey1   demo 
2  Rah  rah11   unkey2   demo1 
3  dee  dee11   unkey3   demo2 

// db_like

id || post_id || unique_key 

1   2   unkey3 

我的问题是,如何搭配这根据两个表到unique_key f在表db_post

//输出应该如下所示。 (WHERE unique_key ='unkey3')

id || name || unique_key || pub 

3  dee   unkey3  demo2 
2  Rah   unkey3  demo1 -> Result from table db_like 
+0

为混合表采取厨房龙头或任何其他随机函数。你在找什么是JOIN。有两种主要类型的连接INNER JOIN和LEFT JOIN,在这里你需要左连接。 –

我不明白为什么被@tango给出的答案已被接受,查询不给欲望的输出,它返回:

id || name || unique_key || id 
3  dee  unkey3   1 

事实上,我不明白如何通过单个连接连接这两个表来获得您在问题中编写的输出。

要么你加入使用表使用unique_key列,例如:

select db_post.id, db_post.name, db_post.unique_key, db_post.pub 
from db_post 
left join db_like on db_post.unique_key = db_like.unique_key 
where db_post.unique_key = 'unkey3'; 

,你获得所需输出的第一行:

id || name || unique_key || pub 
3  dee  unkey3   demo2 

要么你加入使用两个表db_post.id = db_like.post_id

select db_post.id, db_post.name, db_like.unique_key, db_post.pub 
from db_post 
left join db_like on db_post.id = db_like.post_id 
where db_like.unique_key = 'unkey3'; 

并且您获得所需输出的第二行:

id || name || unique_key || pub 
2  Rah  unkey3   demo1 

要获得你必须使用union两行:

select db_post.id, db_post.name, db_post.unique_key, db_post.pub 
from db_post 
left join db_like on db_post.unique_key = db_like.unique_key 
where db_post.unique_key = 'unkey3' 
union 
select db_post.id, db_post.name, db_like.unique_key, db_post.pub 
from db_post 
left join db_like on db_post.id = db_like.post_id 
where db_like.unique_key = 'unkey3'; 

根据我的理解,您正在为所述问题询问SQL。如果是这种情况,那么以下将在两个表之间进行连接。

select p.id, p.name, p.unique_key, l.id 
from db_post p 
left outer join db_like l on 
p.unique_key = l.unique_key 
where p.unique_key='unkey3' 

如果我的评论满足您的问题,请将其标记为正确的答案,以便将来帮助其他读者。

+0

只需再次查看问题,我只需要给定'unique_key'的结果。现在它显示所有表值。 –

+0

你可以添加where子句给定的唯一键,让我更新我的评论 – tango

+0

为什么这个答案被接受?该查询不提供所需的输出。 – Xebax

使用此代码连接两个表

select a.id, a.name, a.unique_key 
from db_post a, db_like b WHERE 
a.unique_key = b.unique_key AND a.unique_key='unkey3' GROUP BY a.unique_key