2010-10-25 53 views
0

如果我有三個表,我通過所有帖子試圖循環:顯示從關係的關係MySQL的結果

posts: post_id, post_title, post_content 
tag_relations: post_id, tag_id 
tags: tag_ig, tag_name 

如果每個職位將有多個標籤,我將如何顯示每個標籤爲每個職位?

因爲,我將如何設置我的SQL查詢,以及如何打印結果?使用多個查詢會更容易嗎?

回答

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找回沒有任何標籤的帖子。

+0

與左連接,如果你想檢索沒有標籤的帖子 – 2010-10-25 23:58:35

+0

@Alfonso:更新我的答案與關於這一點的筆記。 – 2010-10-26 00:01:52

+0

多數民衆贊成在我正在尋找,感謝您的幫助! – Booski 2010-10-26 02:34:08