如果我有三张桌子,我正试图遍历所有帖子:
posts: post_id, post_title, post_content
tag_relations: post_id, tag_id
tags: tag_ig, tag_name
如果每个帖子都有多个标签,我如何显示每个帖子的每个标签?
同样如何,我将如何设置SQL查询,以及如何打印结果?使用多个查询会更容易吗?
答案 0 :(得分:1)
MySQL提供了有用的GROUP_CONCAT()
函数,您可以按如下方式使用它:
SELECT p.post_id, p.post_title, GROUP_CONCAT(tag_name SEPARATOR ', ') tags
FROM posts p
JOIN tag_relations tr ON (tr.post_id = p.post_id)
JOIN tags t ON (t.tag_id = tr.tag_id)
GROUP BY p.post_id;
测试用例:
CREATE TABLE posts (post_id int, post_title varchar(50));
CREATE TABLE tags (tag_id int, tag_name varchar(50));
CREATE TABLE tag_relations (post_id int, tag_id int);
INSERT INTO posts VALUES (1, 'post 1');
INSERT INTO posts VALUES (2, 'post 2');
INSERT INTO posts VALUES (3, 'post 3');
INSERT INTO tags VALUES (1, 'mysql');
INSERT INTO tags VALUES (2, 'sql');
INSERT INTO tags VALUES (3, 'javascript');
INSERT INTO tags VALUES (4, 'python');
INSERT INTO tag_relations VALUES (1, 1);
INSERT INTO tag_relations VALUES (1, 2);
INSERT INTO tag_relations VALUES (2, 3);
INSERT INTO tag_relations VALUES (3, 2);
INSERT INTO tag_relations VALUES (3, 4);
结果:
+---------+------------+-------------+
| post_id | post_title | tags |
+---------+------------+-------------+
| 1 | post 1 | mysql, sql |
| 2 | post 2 | javascript |
| 3 | post 3 | sql, python |
+---------+------------+-------------+
3 rows in set (0.00 sec)
正如下面评论中提到的@Alfonso de la Osa,您可以使用left outer joins代替inner joins来取回没有任何标记的帖子。