我加了一些測試數據,你的表:
INSERT INTO tags VALUES (1, 'mysql');
INSERT INTO tags VALUES (2, 'javascript');
INSERT INTO tags VALUES (3, 'c++');
INSERT INTO users VALUES (1, 'user a', 'pass');
INSERT INTO users VALUES (2, 'user b', 'pass');
INSERT INTO users VALUES (3, 'user c', 'pass');
INSERT INTO users_posts VALUES (1, 1, 'some content 1');
INSERT INTO users_posts VALUES (2, 1, 'some content 2');
INSERT INTO users_posts VALUES (3, 2, 'some content 3');
INSERT INTO users_posts VALUES (4, 2, 'some content 4');
INSERT INTO users_posts VALUES (5, 2, 'some content 5');
INSERT INTO users_posts VALUES (6, 3, 'some content 6');
INSERT INTO posts_tags VALUES (1, 1, 1);
INSERT INTO posts_tags VALUES (2, 2, 1);
INSERT INTO posts_tags VALUES (3, 1, 2);
INSERT INTO posts_tags VALUES (4, 3, 2);
INSERT INTO posts_tags VALUES (5, 2, 3);
INSERT INTO posts_tags VALUES (6, 2, 4);
INSERT INTO posts_tags VALUES (7, 3, 4);
INSERT INTO posts_tags VALUES (8, 1, 5);
INSERT INTO posts_tags VALUES (9, 2, 6);
INSERT INTO posts_tags VALUES (10, 3, 6);
然後去除GROUP BY
:
SELECT *
FROM users
INNER JOIN users_posts ON users_posts.user_id = users.user_id
INNER JOIN posts_tags ON users_posts.id = posts_tags. users_posts_id
INNER JOIN tags ON posts_tags.tag_id = tags.id
WHERE tags.tag = 'mysql';
返回:
+---------+--------+------+----+---------+----------------+----+--------+----------------+----+-------+
| user_id | name | pass | id | user_id | content | id | tag_id | users_posts_id | id | tag |
+---------+--------+------+----+---------+----------------+----+--------+----------------+----+-------+
| 1 | user a | pass | 1 | 1 | some content 1 | 1 | 1 | 1 | 1 | mysql |
| 1 | user a | pass | 2 | 1 | some content 2 | 3 | 1 | 2 | 1 | mysql |
| 2 | user b | pass | 5 | 2 | some content 5 | 8 | 1 | 5 | 1 | mysql |
+---------+--------+------+----+---------+----------------+----+--------+----------------+----+-------+
3 rows in set (0.00 sec)
這是博文中只一行,只要th電子郵件不會使用同一標籤多次標記。事實上,爲了防止這種情況發生,你可能要考慮消除posts_tags
的surrogate key和使用上(tag_id, users_posts_id)
複合主鍵:
CREATE TABLE posts_tags (
tag_id INT UNSIGNED NOT NULL,
users_posts_id INT UNSIGNED NOT NULL,
PRIMARY KEY (tag_id, users_posts_id)
);
你能提供你期待的輸出的例子嗎? – 2010-08-11 02:01:22
@Daniel Vassallo我期待顯示與該特定標籤相關的所有帖子。 – pops 2010-08-11 02:02:44
擺脫「GROUP BY」,但除此之外,我可以看到的唯一問題是您認爲存在的數據,不是 – 2010-08-11 02:07:23