繁体   English   中英

如何使用公共字段在mysql中联接两个表

[英]how to join two tables in mysql using a common field

我有两个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

我的问题是,如何根据表db_post中的unique_key字段将这两个表混合使用。

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

id  ||  name  ||  unique_key  ||  pub   ||  post_id

3       dee         unkey3       demo2       {null}
2       Rah         unkey2       demo1        2
1       Jit         unkey1       demo        {null}

id从现场db_postpost_id从现场db_like应该匹配。

这需要左连接,其连接条件为db_unique_key = db_like.unique_key and db_like.unique_key='unkey3')

select
p.id,
p.name,
p.unique_key,
p.pub,
l.post_id
from db_post p
left join db_like l on l.unique_key = p.unique_key and l.unique_key = 'unkey3'
order by p.id desc

unique_key列上使用LEFT JOIN

select dp.id, 
       dp.name, 
       dp.unique_key, 
       dp.pub,
       dl.post_id
from db_post dp 
left join db_like dl on dp.unique_key  = dl.unique_key
order by dp.id desc; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM