我正在尝试查询返回与用户正在阅读的文章相关的3篇文章。为此,我制作了一个表格,其中包含一系列与所有文章相关的标签(最多5个标签,文章)。
这就是我所拥有的:
CREATE TABLE IF NOT EXISTS `j_news` (
`n_id` smallint(5) NOT NULL AUTO_INCREMENT,
`n_title` varchar(94) COLLATE utf8_danish_ci NOT NULL,
`n_text` text COLLATE utf8_danish_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci AUTO_INCREMENT=25 ;
CREATE TABLE IF NOT EXISTS `j_news_tags` (
`nt_id` mediumint(7) NOT NULL AUTO_INCREMENT,
`nt_news_id` mediumint(7) NOT NULL,
`nt_tag` varchar(24) COLLATE utf8_danish_ci NOT NULL,
PRIMARY KEY (`nt_id`),
KEY `nt_news_id` (`nt_news_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci AUTO_INCREMENT=1 ;
答案 0 :(得分:2)
如果您真的考虑过性能I would suggest you read up this question ,那么我前段时间。它处理大型数据库,并具有不同查询的基准(所有处理标签)。
为了缩短它,SQL将是这样的:
SELECT DISTINCT p . *
FROM projects p
JOIN projects_to_tags pt ON pt.project_id = p.num
JOIN projects_to_tags x ON x.tag_id = pt.tag_id
AND x.project_id = x -- x is your project ID number