使用单个查询更新多行


Updating more than one row with a single query

我的数据库中有一个名为posts的表,其中有一列名为has_read。然后我有一个帖子ID数组,如下所示:

$posts = array(1, 5, 29, 38, 50, 51, 52, 65, 79);

我想做的是,对于数组中的所有帖子,更新它们的行,将用户ID添加到has_read中。我不能使用foreach循环,因为它将执行9个查询,我认为这太多了。

$updatestring = implode(",",$posts = array(1, 5, 29, 38, 50, 51, 52, 65, 79))
$sql = "UPDATE post SET has_read=1 WHERE userID IN($updatestring)";

将您的id数组连接到逗号分隔的字符串中,只需使用IN()函数进行批量更新

尽管实际思考起来,这是完全错误的做法。由于这是一种一个线程对多个用户的关系,因此最好有一个标准化的数据库,并使用一个单独的表来跟踪基于用户id和线程id的读取。

您可以像这样使用WHERE IN语句:

$result = mysql_query('UPDATE table SET field = value WHERE id IN ('.implode(',',$posts).')');

您可以使用IN.

$sql = "UPDATE posts 
        SET has_read = has_read + " . $user_id . "
        WHERE id IN (" . implode(",", $posts) . ")";

当然,您不应该按照这种方式进行操作,而是准备一条语句并将$user_id作为参数传递,具体取决于您使用的数据库库。

WhereIN 一起使用

$result = mysql_query('UPDATE posts SET has_read= user_id
WHERE id IN ('.implode(',',$posts).')');

之类的东西怎么样

UPDATE posts_table SET has_read = 1 WHERE id IN (1, 5, 29, 38, 50, 51, 52, 65, 79);

试试这个:

$query = 'UPDATE posts SET has_head = 1 WHERE id IN (' . implode(',', array_map('intval', $array)) . ');';