SQL 使用两个不同的 ID 进行查询

SQL query with two different ids

我需要防止 photo_order 字段超过与文章关联的照片数量。我有这个,但它不起作用。 Table 名称已被使用两次,可能是错误的。

UPDATE articles_photos SET photo_order = 
    IF(photo_order < (SELECT COUNT(id) FROM articles_photos
        WHERE article_id = 12), photo_order + 1, 1) WHERE id = 26

如何解决上述问题?我的数据库是 MySQL.

我认为这是您遇到的错误:

You can't specify target table 'articles_photos' for update in FROM clause

下面是将 cross join 与子查询一起使用的解决方法:

update articles_photos ap
cross join (select count(id) cnt from articles_photos where article_id = 12) temp
set ap.photo_order = if(ap.photo_order<temp.cnt,ap.photo_order+1,1)
where ap.id = 26;