我有这张 table
file_id cat_1 cat_2 cat_3
cat1
、cat2
、cat3
均包含类别 ID。
我想选择 cat1
OR cat2
OR cat3
简单查询是:
SELECT file_id FROM files WHERE
cat_1 IN (1,2,3,4,5)
OR cat_2 IN (1,2,3,4,5)
OR cat_3 IN (1,2,3,4,5)
没有更好的方法吗?例如将所有列放入另一个列表中?
WHERE (cat_1,cat_2,cat_3) IN (1,2,3,4,5) ?
最佳答案
更好的数据库设计是
files table
-----------
id
name
...
categories table
----------------
id
name
...
file_categories table
---------------------
file_id
category_id
这样您就可以在每个文件中存储任意数量的类别。要获取特定类别的所有文件,您可以执行以下操作
select f.*
from files f
join file_categories fc on fc.file_id = f.id
join categories c on fc.category_id = c.id
where c.name = 'cat 1'
或者如果您已经有 category_id
列表,则执行
select f.*
from files f
join file_categories fc on fc.file_id = f.id
where fc.category_id in (1,2,3,4,5)
关于mysql - 通过在 MySQL 中搜索多列和多个值来选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29591341/