drnvcm3949 2013-01-25 19:11
浏览 295
已采纳

在MySQL数据库中搜索标签

I'm working on creating a system to allow users to upload items and add 'tags' to them to help them be visible in searches. Currently, I have a database that works like this:

id|title|tags

Where tags is a comma-separated list of tags the user has entered themself. I've read that this is a terrible way to do it, but having a tags table and storing each ID along with the item record is basically the same thing.

How could I run a search to return the most relevant results first? I'm using this at the moment, which works, but doesn't sort by relevancy: SELECT * FROM items WHERE tags LIKE '%$tag%' LIMIT 0,20"; where $tag is just a tag, no commas (it's inside a loop).

  • 写回答

1条回答 默认 最新

  • dongzhuner6981 2013-01-25 19:16
    关注

    having a tags table and storing each ID along with the item record is basically the same thing

    NO. NO. NO. It's definitely not the same thing.

    You take your "comma separated listed" version, and try to come up with the queries to accomplish these problems:

    1. delete tag ID #7 from all titles
    2. How many titles use tag #87

    With a properly normalized table:

    1. DELETE FROM users_tags WHERE tag_id=7
    2. SELECT count(*) FROM users_tags WHERE tag_id = 87

    With your version:

    1. UPDATE users_tags SET tags=.... insert massively ugly string operation here ...
    2. SELECT count(*) FROM users_tags WHERE tag_id=87 OR tag_id='87,%' OR tag_id LIKE '%,87,%' or tag_id LIKE '%,87'

    see the difference?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办