[英]Select from two rows in the same table with SQL
| postid | ref_postid | title |
| 1 | 0 | Title 1 |
| 2 | 1 | |
| 3 | 1 | |
| 4 | 0 | Title 2 |
| 5 | 4 | |
這是討論論壇的表格。 當ref_postid = 0時,這意味着它是主要帖子。 當ref_postid不為0時,它是一個答案並引用了一個postid,請參見上面的表格示例。 (只有主要帖子才有標題。)
我想選擇表中的所有行,但是問題是我想顯示答案所涉及的討論的標題。
示例:假設我想要postid = 2的行,我也想獲取“ Title 1”,這是討論的名稱。
我嘗試使用CASE進行操作,但出現錯誤。 我不是很擅長此事。 一個查詢是否可行? 還是我必須使用兩個查詢?
謝謝你的幫助!
select ifnull(q.title, a.title) title, ... (other columns)
from posts a
left join posts q on a.ref_postid <> 0 and a.ref_postid = q.postid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.