I’m struggling with a join. Basically I want the tags results from my query to be in a single row.
Below are my tables:
covercategorycover_tagtag
The query returns the cover, category, and all tags for that category. NULL results in the tags are allowed, this is so I get all covers regardless if there are no tags added to it.
In the database I have 2 rows in the covers. The 1st cover has 3 tags, the 2nd cover has no tags. When running the query below I get 4 rows. 3 of them are the 1st cover, with a different tag, the 4th is the row without any tags.
I basically want 2 results with all the tags for each cover within the one row. Is this possible?
SELECT *
FROM cover
JOIN category ON cover.category_id = category.id
LEFT OUTER JOIN cover_tag ON cover_tag.cover_id = cover.id
LEFT OUTER JOIN tag ON cover_tag.tag_id = tag.id
Data from phpMyAdmin
CREATE TABLE `category` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `category` VALUES(1, 'Cars', 'cars');
INSERT INTO `category` VALUES(2, 'Music', 'music');
INSERT INTO `category` VALUES(3, 'Abstract', 'abstract');
CREATE TABLE `cover` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`category_id` int(9) NOT NULL,
`title` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `cover` VALUES(1, 1, 'Red Ferarri', 'red-ferarri', 'redferrari.jpg', '2011-12-20 23:48:11');
INSERT INTO `cover` VALUES(2, 1, 'Ford Focus ST', 'ford-focus-st', 'focuss.jpg', '2011-12-20 23:48:11');
CREATE TABLE `cover_tag` (
`cover_id` int(9) NOT NULL,
`tag_id` int(9) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `cover_tag` VALUES(1, 1);
INSERT INTO `cover_tag` VALUES(1, 2);
INSERT INTO `cover_tag` VALUES(1, 3);
CREATE TABLE `tag` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`tag` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `tag` VALUES(1, 'cars');
INSERT INTO `tag` VALUES(2, 'ferarri');
INSERT INTO `tag` VALUES(3, 'speed');
You can Concatenate them with
GROUP_CONCATwith group by, something like this:This will give you the following: