使用COUNT INSERT INTO和子查询

时间:2016-06-09 19:33:07

标签: mysql sql select insert subquery

我想将照片数据放到表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) 中,并根据所选文章的照片数量进行调整。

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

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

phpmyadmin说:

@using System.Web.Optimization


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>LinkShortener</title>
    @Styles.Render("~/bundles/css/")
    @Scripts.Render("~/bundles/app/libs/")
    @Scripts.Render("~/bundles/app/webapp/")
</head>
<body ng-app="app"></body>

我错了什么?

1 个答案:

答案 0 :(得分:4)

你很亲密。我相信以下内容可行:

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;

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