php - 将一个字段与存储在 mySQL 中的多个 ID 匹配的最佳方法是什么

标签 php mysql sql

我有一个表,其中有一列称为“所有者”,其中包含与该特定记录相关联的用户的 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/

相关文章:

php - Laravel eloquent - 使用带有关系的可选值键参数进行查询

PHP:带有链接表的 MYSQL COUNT 查询

php - 如何从 PHP 将 Excel 文件导入 mysql 数据库

mysql - 关于数据库建模

mysql - Hibernate:是否可以在命名查询中同时使用Like和In?

python - Numpy 数组到 SQL 表

php - base_url() 函数在错误页面上不起作用。即使在自动加载之后

php使用循环重新启动脚本执行的时间限制

php - phalcon 更新前自动选择

mysql - 查询在 SQL Server 中工作但在 mySQL 中不起作用