V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
zjttfs
V2EX  ›  MySQL

请教在不固定分类的情况下多选分类该如何更好的查询?

  •  
  •   zjttfs · 2021-02-19 11:01:09 +08:00 · 1158 次点击
    这是一个创建于 1155 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求: 动态增减分类(2 级),音乐可以选择 0-n 个分类,用户可以选择 0-n 个分类来筛选结果.

    我现在设计的表结构为:

    分类表 cate

    cate.jpg

    音乐表 sound

    sound.jpg

    音乐的分类表 sound_cate

    sound_cate.jpg


    想请教下这样的表结构是否合理,是否有更好的方式? 然后我该怎么查询效率较高?

    我现在用的子查询来查询,但效率实在太低了.

    SELECT id,title from sound  
    where 
    status=50  
    and 
    (SELECT count(id) from sound_cate where sound_id=sound.id and cate_id in (8,1,9,14))=3 
    order by id desc
    
    6 条回复    2021-02-20 11:25:55 +08:00
    xuanbg
        1
    xuanbg  
       2021-02-19 11:21:57 +08:00   ❤️ 1
    你这个多对多的不适合用分类,用 tag 更好。
    zjttfs
        2
    zjttfs  
    OP
       2021-02-19 11:36:05 +08:00
    @xuanbg 还有一个 tag 字段和 tag 相关的表, 我没有列出来.
    现在需求这样,我也很头疼..
    zhuangjia
        3
    zhuangjia  
       2021-02-19 11:51:01 +08:00
    (SELECT count(id) from sound_cate where sound_id=sound.id and cate_id in (8,1,9,14))=3

    这个条件是要实现什么需求
    zjttfs
        4
    zjttfs  
    OP
       2021-02-19 11:56:57 +08:00
    @zhuangjia
    这里写的有点问题,
    应该是
    (SELECT count(id) from sound_cate where sound_id=sound.id and cate_id in (8,1,9,14))=4

    找出含有分类 8,1,9,14 的音乐
    zhuangjia
        5
    zhuangjia  
       2021-02-20 10:28:42 +08:00   ❤️ 1
    @zjttfs 200 多点击了,再等等看有没有人来优化 orz
    zjttfs
        6
    zjttfs  
    OP
       2021-02-20 11:25:55 +08:00
    @zhuangjia sound_cate 做下 sound_id 与 cate_id 的联合索引 , 性能也还可以.
    但感觉效率不是很高,暂时还没有做大数据下的负载测试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   990 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:42 · PVG 06:42 · LAX 15:42 · JFK 18:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.