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 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误