I have this query that should display all posts related to a
specific tag but for some reason it will only display one result instead of all the results can some one help me fix this problem?
Here is MySQL code.
"SELECT users.*, users_posts.*, tags.*, posts_tags.*,
FROM users
INNER JOIN users_posts ON users_posts.user_id = users.user_id
INNER JOIN posts_tags ON users_posts.id = posts_tags.posts_id
INNER JOIN tags ON posts_tags.tag_id = tags.id
WHERE tags.tag = '" . $tag_id . "'
GROUP BY tags.tag"
Here is my MySQL table.
CREATE TABLE posts_tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag_id INT UNSIGNED NOT NULL,
users_posts_id INT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE users_posts (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
pass CHAR(40) NOT NULL,
PRIMARY KEY (user_id)
);
I added some test data to your tables:
Then removing the
GROUP BY:Returns:
It’s just one row per post, as long as the posts are not tagged with the same tag more than once. In fact, to prevent this from happening, you may want to consider eliminating the surrogate key in
posts_tagsand use a composite primary key on(tag_id, users_posts_id):