Skip to content

Instantly share code, notes, and snippets.

@harikt
Created September 16, 2011 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harikt/1221289 to your computer and use it in GitHub Desktop.
Save harikt/1221289 to your computer and use it in GitHub Desktop.
Post and Tags Relation
-- Adminer 3.2.2 MySQL dump
SET NAMES utf8;
SET foreign_key_checks = 0;
SET time_zone = 'SYSTEM';
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `posts`;
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(300) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `posts` (`id`, `title`, `content`) VALUES
(1, 'test 1', 'test 1'),
(2, 'test 2', 'test 2'),
(3, 'test 3', 'test 3'),
(4, 'test 4', 'test 4'),
(5, 'test 5', 'test 5'),
(6, 'test 6', 'test 6'),
(7, 'test 7', 'test 7');
DROP TABLE IF EXISTS `posts_tags`;
CREATE TABLE `posts_tags` (
`post_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `posts_tags` (`post_id`, `tag_id`) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 1),
(2, 4);
DROP TABLE IF EXISTS `tags`;
CREATE TABLE `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(300) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `tags` (`id`, `name`) VALUES
(1, 'tag1'),
(2, 'tag2'),
(3, 'tag3'),
(4, 'tag4'),
(5, 'tag5');
-- 2011-09-16 11:14:08
Query to select all tags in a single query with tags concatenated .
SELECT p.*,
( SELECT GROUP_CONCAT(t.name) as tag_name
FROM posts_tags as pt, tags as t
WHERE pt.post_id = p.id
AND pt.tag_id = t.id ) as tag_name
FROM posts as p WHERE p.id = 1
@harikt
Copy link
Author

harikt commented Sep 16, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment