2015-08-08 157 views
0

我有兩個mysql表。即,如何加入兩個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 

我的問題是,如何搭配這根據兩個表到unique_key f在表db_post

//輸出應該如下所示。 (WHERE unique_key ='unkey3')

id || name || unique_key || pub 

3  dee   unkey3  demo2 
2  Rah   unkey3  demo1 -> Result from table db_like 
+0

爲混合表採取廚房龍頭或任何其他隨機函數。你在找什麼是JOIN。有兩種主要類型的連接INNER JOIN和LEFT JOIN,在這裏你需要左連接。 –

回答

2

我不明白爲什麼被@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'; 
1

根據我的理解,您正在爲所述問題詢問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' 

如果我的評論滿足您的問題,請將其標記爲正確的答案,以便將來幫助其他讀者。

+0

只需再次查看問題,我只需要給定'unique_key'的結果。現在它顯示所有表值。 –

+0

你可以添加where子句給定的唯一鍵,讓我更新我的評論 – tango

+0

爲什麼這個答案被接受?該查詢不提供所需的輸出。 – Xebax

0

使用此代碼連接兩個表

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