Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 插入到并使用COUNT插入子查询_Mysql_Sql_Select_Insert_Subquery - Fatal编程技术网

Mysql 插入到并使用COUNT插入子查询

Mysql 插入到并使用COUNT插入子查询,mysql,sql,select,insert,subquery,Mysql,Sql,Select,Insert,Subquery,我想把照片数据放在表articles\u photos中,并用所选文章的照片数对其进行调整 两个表都存在。下面我提出了我的问题 INSERT INTO articles_photos(title, filename, photo_order, created, art

我想把照片数据放在表articles\u photos中,并用所选文章的照片数对其进行调整

两个表都存在。下面我提出了我的问题

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;

您应该能够从插入的同一个表中进行选择,但不能像在问题中那样在值列表中的子查询中进行选择。相反,在这里,我们只是将所有常量下移到SELECT语句中。

在插入数据的子查询中不能使用同一个表。错误很明显:1093-表'articles_photos'指定了两次,既作为'INSERT'的目标,又作为数据的单独源。我应该使用两个单独的查询,获取行数,然后进行第二个查询吗?我能做我在一个查询中描述的吗?JNevill的答案很好,我只是测试这个查询,然后你给出答案。我只输给你38秒。你在计数时错过了+1。@MahediSabuj我经常遇到这种情况。我倾向于比这里的许多其他海报更彻底,结果常常输掉比赛。每隔一段时间我就可以先把一个挤进去。刚刚添加了+1。