如何选择所有帖子的标签?

时间:2016-06-18 15:50:11

标签: mysql sql

我有这张桌子:

// QandA
+----+--------+----------------------------------------+------+---------+
| id |  title |                  content               | type | related |
+----+--------+----------------------------------------+------+---------+
| 1  | title1 | content of question1                   | 0    | NULL    |
| 2  |        | content of first answer for question1  | 1    | 1       |
| 3  | title2 | content of question2                   | 0    | NULL    |
| 4  | title3 | content of question3                   | 0    | NULL    |
| 5  |        | content of second answer for question1 | 1    | 1       |
| 6  |        | content of first answer for question3  | 1    | 4       |
| 7  | title4 | content of question4                   | 0    | NULL    |
| 8  |        | content of first answer for question2  | 1    | 3       |
+----+--------+----------------------------------------+------+---------+
-- type colum: it is 0 for questions and 1 for answers.
-- related column: it is NULL for questions and {the id of its own question} for answers.

我还有另外两张表:

// interface_tags
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1       | 1      |
| 1       | 5      |
| 3       | 4      |
| 4       | 1      |
| 4       | 2      |
| 4       | 5      |
| 7       | 2      |
+---------+--------+

// tags
+----+----------+
| id | tag_name |
+----+----------+
| 1  | PHP      |
| 2  | SQL      |
| 3  | MySQL    |
| 4  | CSS      |
| 5  | Java     |
| 6  | HTML     |
| 7  | JQuery   |
+----+----------+

这是我的疑问:

SELECT id,
       title,
       content
FROM QandA
WHERE id = :id1 OR related = :id2

-- Note: :id1, :id2 are identical

如您所见,它会选择问题(id = :id2)及其所有答案(related = :id3)。

我的问题是什么?我还需要选择所有问题的标签。这是预期的输出:

-- :id = 1

// QandA
+----+--------+----------------------------------------+------------+
| id |  title |                  content               |   tag      |
+----+--------+----------------------------------------+------------+
| 1  | title1 | content of question1                   | PHP,JAVA   |
| 2  |        | content of first answer for question1  |            |
| 5  |        | content of second answer for question1 |            |
+----+--------+----------------------------------------+------------+

我该怎么做?

2 个答案:

答案 0 :(得分:3)

你可以试试这个

SELECT 
   q.id,
   q.title,
   q.content,
   GROUP_CONCAT(t.tag_name) AS tag
FROM QandA q
LEFT JOIN interface_tags it ON it.post_id = q.id AND q.type = 0
LEFT JOIN tags t ON t.id = it.tag_id
WHERE q.id = :id1 OR related = :id2
GROUP BY q.id

SQLFiddle中查看架构和脚本执行。

答案 1 :(得分:1)

您可以使用QANDA tbale的LEFT联接

     SELECT 
       a.id,
       a.title,
       a.content,
       group_concat(c.tag_name)
    FROM QandA as a
    INNER JOIN interface_tags as b  on ( a.id = b.post_id  and a.type='0')
    INNER JOIN tags as c on b.tag_id  = c.id
    LEFT  JOIN QandA as d on ( a.id = d.id and d.type ='1')
    WHERE a.id = :id1 OR a.related = :id2
    group by a.id