Cli*_*ote 2 php mysql database database-design
我有2张桌子:
标签表的结构如下:
因此,对于为帖子指定的每个标记,我都会在tags表中创建一条记录.如果帖子有10个标签,则标签表中将有10个记录与该post_id.
我现在正在尝试构建一个搜索页面,用户可以在其中搜索标签不包含给定关键字的帖子.但这会产生问题.像这样的查询:
SELECT DISTINCT posts.id, posts.title, posts.content
FROM jobs, tags
WHERE tags.tag NOT LIKE '%$keywords%' AND posts.id=tags.post_id
Run Code Online (Sandbox Code Playgroud)
不起作用,因为如果一个帖子有6个标签,其中一个有关键字,它仍然会被返回,因为标签表中的其他5个记录没有该关键字.
解决这个问题的最佳方法是什么?除了在posts表中创建一个新列以外,还有什么方法可以存储所有用于搜索的逗号分隔标记?
确保你有索引或这将表现非常糟糕:
SELECT posts.id, posts.title, posts.content
FROM posts
WHERE NOT EXISTS (
SELECT post_id from tags
WHERE tags.tag LIKE '%$keywords%'
AND posts.id=tags.post_id
)
Run Code Online (Sandbox Code Playgroud)
这会获得所有帖子的列表,不包括那些标签与您指定的标签匹配的帖子.(您的原始查询引用了'jobs'表.我认为这是'帖子'的拼写错误.)
表别名使这个更清洁:
SELECT p.id, p.title, p.content
FROM posts p
WHERE NOT EXISTS (
SELECT t.post_id from tags t
WHERE t.tag LIKE '%$keywords%'
AND p.id=t.post_id
)
Run Code Online (Sandbox Code Playgroud)
然后,我将创建这些索引:
Posts: id, tag_id
Tags: post_id, tag
Run Code Online (Sandbox Code Playgroud)
然后,使用' explain ' 运行查询,看看它是否表现良好.用结果更新您的问题,有人会提供进一步的建议.索引调整比其他任何东西都更多的试验和错误,所以测试确实是必要的.