duanlei2458 2016-12-24 13:54
浏览 431
已采纳

SQL仅获取与逗号分隔的完整数字匹配的行

I'm working on something that shows shops under a specific category, however I have an issue because I store the categories of a shop like this in a record with the id of a category. "1,5,12". Now, the problem is if I want to show shops with category 2, it "mistakens" 12 as category 2. This is the SQL right now.

SELECT * FROM shops WHERE shop_cats LIKE '%".$sqlid."%' LIMIT 8

Is there a way to split the record "shop_cats" by a comma in SQL, so it checks the full number? The only way I can think of is to get all the shops, and do it with PHP, but I don't like that as it will take too many resources.

  • 写回答

3条回答 默认 最新

  • dongyingming8970 2016-12-24 14:00
    关注

    This is a really, really bad way to store categories, for many reasons:

    • You are storing numbers as strings.
    • You cannot declare proper foreign key relationships.
    • A (normal) column in a table should have only one value.
    • SQL has poor string functions.
    • The resulting queries cannot take advantage of indexes.

    The proper way to store this information in a database is using a junction table, with one row per shop and per category.

    Sometimes, we are stuck with other people's really bad design decisions. If this is your case, then you can use FIND_IN_SET():

    WHERE FIND_IN_SET($sqlid, shop_cats) > 0
    

    But you should really fix the data structure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable