MySQL Select 列包含列表元素的行
MySQL Select row where column contains elements from a list
我目前正在开发一个包含视频的多个类别的网站。
我的问题:每个视频都有多个类别,但我不知道如何搜索它:
Select * from table where category (contains the exact item)
我已经想到了 LIKE 运算符,但是当有多个类别包含相同的词时(例如:'cats_playing_with_balls'、'dogs_playing_with_balls').
修复您的数据模型!不要在单个列中存储多个值。相反,您应该有一个单独的 table 来存储视频和类别之间的关系。
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);
我目前正在开发一个包含视频的多个类别的网站。 我的问题:每个视频都有多个类别,但我不知道如何搜索它:
Select * from table where category (contains the exact item)
我已经想到了 LIKE 运算符,但是当有多个类别包含相同的词时(例如:'cats_playing_with_balls'、'dogs_playing_with_balls').
修复您的数据模型!不要在单个列中存储多个值。相反,您应该有一个单独的 table 来存储视频和类别之间的关系。
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);