[英]how to join two tables in mysql using a common field
我有兩個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字段將這兩個表混合使用。
//輸出應如下所示。 (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_post
和post_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.