Jithin Varghese
Jithin Varghese

Reputation: 2228

how to join two tables in mysql using a common field

I have two mysql tables. ie,

  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

My question is, how to mix this two tables according to unique_key field in table db_post.

//output should be like below. (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 field from db_post and post_id field from db_like should match.

Upvotes: 0

Views: 30

Answers (2)

Rahul
Rahul

Reputation: 77866

Using a LEFT JOIN on unique_key column like

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; 

Upvotes: 1

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

This needs left join with the joining condition as 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

Upvotes: 2

Related Questions