[英]how to join two mysql tables
我有两个mysql表。 即
// 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
我的问题是,如何根据表db_post
unique_key
字段将这两个表混合db_post
。
//输出应如下所示。 (WHERE unique_key ='unkey3')
id || name || unique_key || pub
3 dee unkey3 demo2
2 Rah unkey3 demo1 -> Result from table db_like
我不明白为什么@tango给出的答案已经被接受,查询没有给出期望的输出,它返回以下内容:
id || name || unique_key || id
3 dee unkey3 1
实际上,我看不到如何通过一次连接将这两个表连接在一起而获得在问题中编写的输出。
您可以使用表中的unique_key
列进行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
将两个表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'
如果我的评论满足您的问题,请将其标记为正确的答案,以帮助将来的其他读者。
使用此代码联接两个表
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.