我不明白爲什麼被@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';
爲混合表採取廚房龍頭或任何其他隨機函數。你在找什麼是JOIN。有兩種主要類型的連接INNER JOIN和LEFT JOIN,在這裏你需要左連接。 –