我有两张这样的表:
// questions_and_answers
+----+---------------+------------------------+---------+---------+
| id | subject | body | related | deleted |
+----+---------------+------------------------+---------+---------+
| 1 | subject1 | question1 | NULL | 0 |
| 2 | | answer1 | 1 | 0 |
| 3 | subject2 | question2 | NULL | 0 |
| 4 | | answer2 | 3 | 1 |
| 5 | | answer3 | 3 | 0 |
| 6 | subject3 | question3 | NULL | 1 |
| 7 | | answer4 | 6 | 0 |
+----+---------------+------------------------+---------+---------+
-- related column contains either NULL for questions or the id of its question for answers
// viewed_times
+----+-------------+---------+
| id | question_id | user_id |
+----+-------------+---------+
| 1 | 1 | 123 |
| 2 | 1 | 456 |
| 3 | 6 | 123 |
| 4 | 3 | 123 |
| 5 | 6 | 456 |
| 6 | 1 | 789 |
+----+-------------+---------+
我需要搜索body
的问题和答案。
EX1:以下是answer4
条目的预期结果:
+------------------+--------------+-----------------------+
| question_subject | body | total_question_viewed |
+------------------+--------------+-----------------------+
| subject3 | answer4 | 2 |
+------------------+--------------+-----------------------+
EX2:以下是question1
的预期结果:
+------------------+--------------+-----------------------+
| question_subject | body | total_question_viewed |
+------------------+--------------+-----------------------+
| subject1 | question1 | 3 |
+------------------+--------------+-----------------------+
这是我的问题:
SELECT COALESCE(qa2.subject, qa1.subject) question_subject,
qa1.body
FROM questions_and_answers qa1
LEFT JOIN questions_and_answers qa2 ON qa1.related = qa2.id
WHERE qa1.body = ":entry"
我当前的查询返回预期结果的前两列。如何计算total_question_viewed
值?
重点是,有时我必须加入qa1.id
与viewed_times.question_id
,有时我必须加入qa2.id
等于viewed_times.question_id
。我该怎么处理?
答案 0 :(得分:1)
您可以使用coalesce
加入右栏:
select subject as question_subject,
body,
count(*) as total_question_viewed
from questions_and_answers qa
inner join viewed_items v
on coalesce(qa.related, qa.id) = v.question_id
where body like '%answer4%'
group by question_subject, body, v.question_id
答案 1 :(得分:0)
如果我理解正确,这是另一个JOIN
和GROUP BY
:
SELECT COALESCE(qa2.subject, qa1.subject) as question_subject,
qa1.body,
COUNT(vt.question_id)
FROM questions_and_answers qa1 LEFT JOIN
questions_and_answers qa2
ON qa1.related = qa2.id LEFT JOIN
viewed_times vt
ON vt.question_id = qa1.id
WHERE qa1.body = ":entry"
GROUP BY question_subject, qa1.body;