簡體   English   中英

如何聯接兩個mysql表

[英]how to join two mysql tables

我有兩個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字段將這兩個表混合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列進行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將兩個表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';

據我了解,您正在要求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'

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

使用此代碼聯接兩個表

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM