我有两个mysql表。IE,
// 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
table中的字段来混合这两个表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
列的表进行联接,如下所示:
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';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句