I have two tables.
One table holds tags:
CREATE TABLE `tags` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(30) NOT NULL
) COMMENT='';
INSERT INTO `tags` (`id`, `name`) VALUES
(1, 'tag one'),
(2, 'tag two'),
(3, 'tag three'),
(4, 'tag four'),
(5, 'tag five');
Other table holds items, where each item has zero or more tags (their IDs) separated by comma:
CREATE TABLE `items` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(30) NOT NULL,
`tags` text NOT NULL
) COMMENT='';
INSERT INTO `items` (`id`, `name`, `tags`) VALUES
(1, 'first item', '2,4'),
(2, 'second item', ''),
(3, 'third item', '1'),
(4, 'fourth item', '1,3,4');
How do I select only those items which have at least one of the wanted, say (2,3)
tags?
tags.name
column is fine. What is wrong is the comma separated list. This should be replaced with an intermediate table. then you will be properly referencing thetags(id)
. Now you can have silly values in theitems(tags)
column, values like'1,2,3,1,1,2,2,5789'
where a tag is "referenced" twice or a tag that doesn't exist is referenced.