我有一个表,其中有一列称为“所有者”,其中包含与该特定记录相关联的用户的 IDS。
我目前用“,”分隔数据。例如
ID | Name | Owners
1 | Bob | 1,4,5
在对此进行选择时,我打算使用以下 SQL:
select * from table where owner='$profile' or owner like '%,$profile%' or owner like '%$profile,%'
但现在我意识到这是有缺陷的(搜索 5 会匹配 5、15、25,甚至 50)。
执行此操作的正确方法是什么?
最佳答案
@Amarnasan 是正确的:不要在用逗号分隔的单个字段中存储多个值!
在 Bill Karwin 的 SQL Antipatterns
一书中,这被称为 Jaywalking 反模式。
正确的方法是创建一个交集表,将 owners
连接到第一个表。您将在交集表中有多行,代表每条记录的多个所有者:
Record_ID | Owners_ID
1 | 1
1 | 4
1 | 5
您的查询将类似于:
select * from table
join intersection_table
where intersection_table.record_id = table.id
and intersection_table.owners_id = '$profile'
关于php - 将一个字段与存储在 mySQL 中的多个 ID 匹配的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863019/