将 where 语句与一系列 ID 一起使用


using where statement with a sequence of ids

在我的表中,我有一列它有一组用户 ID users_id。每个 ID 用逗号( , 分隔)。

例如:users_id = '1,2,3,4,5';

如果我将$id=1传递给我的函数,如何使用where语句?

function($id){
$sql = "select * from content_noti
        where  ??????"
}

您可以在 DB 的字段值中添加前导和尾随,

例如

改变

1,2,3,4,5

,1,2,3,4,5,

以便每个 ID 都有前导和尾随逗号,

现在,更新函数体:

function($id){
  $sql = "select * from content_noti 
        where  users_id LIKE '%,$id,%'"
}

在这种情况下,您没有任何错误的可能性,因为如果您搜索用户 ID 1那么您只会得到1,而不是111111343

工作演示

如果您有多个 id,最好将IN与查询一起使用

$sql = "select * from content_noti where id IN  (?)"

如果您正在寻找反向而不是使用find_in_set

 $sql = "select * from content_noti where FIND_IN_SET(?, id)";

您可以在 mysql 中使用正则表达式:

function($id){
  $sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}
SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'

将多个数据块存储为单个逗号分隔的列对于数据库来说确实是糟糕的设计,如果可能的话,您应该通过制作耦合表并连接它来考虑将其规范化。

上述查询的性能将很糟糕,并且很难维护。