[英]How to get the value of related rows?
我有一張這樣的桌子:
// QandA
+----+----------+----------------+------+---------+-----------+
| id | subject | acceptedanswer | type | related | id_author |
+----+----------+----------------+------+---------+-----------+
| 1 | subject1 | NULL | 0 | NULL | 123 |
| 2 | | 1 | 1 | 1 | 452 |
| 3 | subject2 | NULL | 0 | NULL | 635 |
| 4 | | 1 | 1 | 3 | 432 |
| 5 | | NULL | 1 | 1 | 246 |
+----+----------+----------------+------+---------+-----------+
/* columns explanations:
- acceptedanswer can be NULL, 0, 1. (0 and NULL are identical). (it is NULL for questions)
- type is 0 for questions and 1 for answers.
- related is NULL for questions. For answers is containing the number of its own question
*/
好吧,我有兩個參數:
id
號: $id = 5
id_author
的那個答案$id_author = 246
現在,我正在嘗試獲得以下兩點:
這是我的查詢:
SELECT t2.subject
FROM qanda t1
JOIN qanda t2 ON t1.related = t2.id AND t2.type = 0
WHERE t1.id = $id AND t2.id_author = $id_author
當前結果:
+----------+
| subject1 |
+----------+
預期結果:
+----------+---+
| subject1 | 1 |
+----------+---+
-- ^ this 1 means the question of this answer has a accepted answer
-- ^ this should be 0 if there isn't any accepted answer for that question
我怎樣才能做到這一點?
嘗試這個:
SELECT t2.subject, max(COALESCE(t3.accepted, 0))
FROM qanda t1
INNER JOIN qanda t2 ON t1.related = t2.id AND t2.type = 0
INNER JOIN qanda t3 ON t1.related = t3.related
WHERE t1.id = $id AND t2.id_author = $id_author
GROUP BY t3.related
不過,我不確定我是否理解您的意圖。 COALESCE
消除null,並使用max()
來查看是否已接受任何答案。 我假設只有答案在related
列中具有非空值。
另外,也許最好不要在表中保留不同的內容?
如果您想知道答案id = 5
回答的問題是否具有可接受的答案,並假設(如注釋中所述)每個問題只能有一個可接受的答案,那么類似這樣的事情(請注意:兩個聯接)應該起作用。 ..
SELECT x.subject
, y.id IS NOT NULL has_accepted
FROM qanda x
LEFT
JOIN qanda y
ON y.related = x.id
AND y.type = 1
AND y.acceptedanswer = 1
JOIN qanda z
ON z.related = x.id
WHERE x.type = 0
AND z.id = 5;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.