我有这张表:
// 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 | |
+----+--------+----------------------------------------+------------+
我该怎么做?
最佳答案
你可以试试这个
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 中查看模式和脚本执行.
关于mysql - 如何选择所有帖子的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898841/