INSERT INTO 和带有 COUNT 的子查询

INSERT INTO and the subquery with COUNT

我想将照片数据放入 table articles_photos 并使用所选文章的照片数量作为条件。

两个table都存在。下面我提出了我的查询

INSERT INTO articles_photos(title, 
                            filename, 
                            photo_order, 
                            created, 
                            article_id) 
      VALUES ('title', 
              'filename', 
               (SELECT COUNT(id) 
                  FROM articles_photos 
                 WHERE article_id = 7) + 1, 
              NOW(), 
              7)

phpmyadmin 说:

Static analysis:

5 errors were found during analysis.

    A comma or a closing bracket was expected (near "SELECT" at position 109)
    Unrecognized keyword. (near "COUNT" at position 116)
    Unexpected token. (near "(" at position 121)
    Unexpected token. (near "id" at position 122)
    Unexpected token. (near ")" at position 124)

#1093 - Table 'articles_photos' is specified twice, both as a target for 'INSERT' and as a separate source for data

我做错了什么?

你很接近。我相信以下方法会起作用:

INSERT INTO articles_photos(title, 
                        filename, 
                        photo_order, 
                        created, 
                        article_id) 
SELECT 'title', 
    'filename', 
    COUNT(id)+1, 
    now(), 
    7
FROM articles_photos 
WHERE article_id = 7;

您应该能够从要插入的同一个 table SELECT,但是您不能像之前那样在 VALUES 列表中的子查询中执行此操作在你的问题中。相反,在这里,我们只是将所有常量向下移动到 SELECT 语句中。