【问题标题】:MySQL Select row where column contains elements from a list [duplicate]MySQL选择行,其中列包含列表中的元素[重复]
【发布时间】:2021-03-02 01:20:53
【问题描述】:

我目前正在开发一个包含视频的多个类别的网站。 我的问题:我每个视频有多个类别,但我不知道如何搜索:

Select * from table where category (contains the exact item)

我已经想到了 LIKE 运算符,但是当存在多个包含相同单词的类别时,这会导致问题(例如:'cats_playing_with_balls'、'dogs_playing_with_球')。

【问题讨论】:

    标签: mysql sql string csv database-design


    【解决方案1】:

    修复您的数据模型!不要在单个列中存储多个值。相反,您应该有一个单独的表来存储视频和类别之间的关系。

    create table videos (
        video_id int primary key auto_increment,
        ...
    );
    
    create table categories (
        category_id int primary key auto_increment,
        name varchar(50),
        ...
    );
    
    create table video_categories (
        video_id int references videos(video_id),
        category_id int references categories(category_id),
        primary key (video_id, category_id)
    );
    

    那么您的查询可以有效地表示为:

    select v.*
    from videos v
    where exists (
        select 1
        from video_categories vc
        inner join categories c on c.category_id = vc.category_id
        where vc.video_id = v.video_id and c.name = 'my category'
    )
    

    对于您当前的设计,假设类别始终存储为逗号分隔值列表,您可以使用find_in_set()

    select * from videos where find_in_set('my category', categories);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2020-01-30
      • 2018-04-15
      • 2016-04-01
      • 1970-01-01
      • 2011-07-13
      • 2019-06-01
      相关资源
      最近更新 更多