如何根据标签过滤帖子?

时间:2018-06-18 06:36:34

标签: mysql sql

这是我的表结构:

// questions_and_answers
+----+---------------+------------------------+---------+---------+
| id |    subject    |           body         | related | deleted |
+----+---------------+------------------------+---------+---------+
| 1  | subject1      | question1 test         | NULL    | 0       |
| 2  |               | answer1                | 1       | 0       |
| 3  | subject2      | question2 test         | NULL    | 0       |
| 4  |               | answer2                | 3       | 1       |
| 5  |               | answer3   test         | 3       | 0       |
| 6  | subject3      | question3              | NULL    | 1       |
| 7  |               | answer4   test         | 6       | 0       |
+----+---------------+------------------------+---------+---------+
-- related column contains either NULL for questions or the id of its question for answers

// tags
+----+--------+
| id |  name  |
+----+--------+
| 1  | mysql  |
| 2  | php    |
+----+--------+

// pivot 
+-------------+--------+
| question_id | tag_id |
+-------------+--------+
| 1           | 1      |
| 3           | 1      |
| 3           | 2      |
| 6           | 1      |
+-------------+--------+

我需要搜索用特定标签标记的问题(所有答案)。例如,[php]代码和test条目 预期结果

| 3  | subject2      | question2 test         | NULL    | 0       |
| 5  |               | answer3   test         | 3       | 0       |

首先,我需要根据标签过滤帖子。对于[php]代码,这是正确的过滤:

| 3  | subject2      | question2 test         | NULL    | 0       |
| 4  |               | answer2                | 3       | 1       |
| 5  |               | answer3   test         | 3       | 0       |

然后根据条目过滤结果。对于test条目,这是正确的过滤:(与预期结果相同)

| 3  | subject2      | question2 test         | NULL    | 0       |
| 5  |               | answer3   test         | 3       | 0       |

这是我当前的查询,它不支持标记过滤。如何为其添加标记过滤?

SELECT COALESCE(qa2.subject, qa.subject) subject,
       qa.body
FROM questions_and_answers qa
LEFT JOIN questions_and_answers qa2 ON qa.related = qa2.id
WHERE MATCH(qa.subject,qa.body) AGAINST (:entry)

1 个答案:

答案 0 :(得分:0)

试试这个脚本:

select distinct COALESCE(T2.id,T1.id) question_id
    ,COALESCE(T2.subject,T1.subject) subject
    ,COALESCE(T2.body,T1.body) body 
    ,T4.name tagName
from (
  ##To get body and filter body contains [test]   
  select * from questions_and_answers
  where body like '%test%'
) T1
##To get tag and filter tagName [php] 
left join questions_and_answers T2 on T1.related = T2.id
left join pivot  T3 on T3.question_id  = COALESCE(T2.id,T1.id)
left join tags T4 on T4.id = T3.tag_id
where T4.name like '%php%'

<强>结果:

| question_id |  subject |           body | tagName |
|-------------|----------|----------------|---------|
|           3 | subject2 | question2 test |     php |

SQL Fiddle Demo Test Link