简体   繁体   English

MySQL NOT LIKE查询无法正常工作

[英]MySQL NOT LIKE query not working

I have 2 tables: 我有2张桌子:

  • posts 帖子
  • tags 标签

Tags table is structured like this: 标签表的结构如下:

  • post_id POST_ID
  • tag 标签

So for every tag that's given for a post, I create a record in the tags table. 因此,对于为帖子提供的每个标签,我都会在标签表中创建一条记录。 If a post has 10 tags, there will be 10 records in tags table with that post_id. 如果一个帖子有10个标签,则标签表中将有10个带有该post_id的记录。

I'm now trying to build a search page where users can do a search for posts where tags do not contain the given keywords. 我现在正在尝试构建一个搜索页面,用户可以在其中搜索标签不包含给定关键字的帖子。 This creates a problem though. 但这会产生问题。 A query like: 查询如下:

SELECT DISTINCT posts.id, posts.title, posts.content
   FROM jobs, tags
   WHERE tags.tag NOT LIKE '%$keywords%' AND posts.id=tags.post_id

doesn't work because if a post has got 6 tags and one of them has got the keyword, it will still be returned because the other 5 records in the tags table don't have that keyword. 不起作用,因为如果帖子中有6个标签,其中一个具有关键字,则仍会返回,因为标签表中的其他5条记录没有该关键字。

What's the best way to solve this? 解决此问题的最佳方法是什么? Any way other than creating a new column in the posts table which stores all the comma-separated tags used only for search?? 除了在posts表中创建一个新列(存储所有仅用于搜索的逗号分隔标记)以外,还有其他方法吗?

Make sure you have indexes or this will perform very badly: 确保您有索引,否则将导致性能下降:

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
)

This gets a list of all posts, excluding those that have a tag matching the tag you specified. 这将获取所有帖子的列表,但不包括带有与您指定的标签匹配的标签的帖子。 (Your orginal query referenced a 'jobs' table. I assumed that was a typo for 'posts'.) (您的原始查询引用了“职位”表。我认为这是“职位”的错字。)

Table aliases make this a little cleaner: 表别名使它更简洁:

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
)

Then, I'd create these indexes: 然后,我将创建以下索引:

Posts: id, tag_id
Tags: post_id, tag

Then, run your query with ' explain ' to see if it's performing well. 然后,使用“ explain ”运行查询以查看其性能是否良好。 Update your question with the results and someone will offer further advice. 使用结果更新您的问题,然后有人会提供进一步的建议。 Index tuning is more trial and error than anything else so testing really is necessary. 索引调优比其他任何事情都要反复试验,因此测试是非常必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM