sqlite 在SQL中获取嵌套SQL查询中的语法错误

kxxlusnw  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(206)

我制作了一个表‘临时’(x,Train 1,Train 2,..Train 4),有5列。我想用来自表‘Train’(x,y1)和‘Ideal’(x,y1)的计算数据(Train.y1-ideal.y1)填充‘Train 1’列。但是下面的嵌套SQL查询给出了‘SELECT附近的语法错误’。它有什么问题吗?

train=1
with engine.connect() as conn:
  while train<2:
    ideal=1
    col_train='y'+str(train)
    train_no=str(train)
    col_ideal='y'+str(ideal)
    query1=conn.execute(text(("INSERT INTO temporary (train%s) VALUES (SELECT (train.%s-ideal.%s)*(train.%s-ideal.%s) FROM train INNER JOIN ideal ON train.x=ideal.x)")%(train_no,col_train,col_ideal,col_train,col_ideal)))
    train+=1
bq3bfh9z

bq3bfh9z1#

出了什么问题?

我认为您的问题是SELECT ....应该放在括号中。

修复(假设我在正确的位置添加了括号,如果没有,请参见下面的演示)

query1=conn.execute(text(("INSERT INTO temporary (train%s) VALUES ((SELECT (train.%s-ideal.%s)*(train.%s-ideal.%s) FROM train INNER JOIN ideal ON train.x=ideal.x))")%(train_no,col_train,col_ideal,col_train,col_ideal)))

以下是工作SQL的演示(尽管表可能不同):

DROP TABLE IF EXISTS train;
DROP TABLE IF EXISTS ideal;
DROP TABLE IF EXISTS temporary;
CREATE TABLE IF NOT EXISTS train (x INTEGER PRIMARY KEY, train_no INTEGER,col_train TEXT);
CREATE TABLE IF NOT EXISTS ideal (x INTEGER PRIMARY KEY, col_ideal INTEGER, col_train INTEGER);
CREATE TABLE IF NOT EXISTS temporary (train_no INTEGER);
INSERT INTO temporary (train_no) VALUES (
    ( /*<<<<<<<<<< ADDED */
        SELECT (train.col_train-ideal.col_ideal)*(train.col_train-ideal.col_ideal) 
        FROM train INNER JOIN ideal ON train.x=ideal.x
    ) /*<<<<<<<<<< ADDED */
);

当签立时:

INSERT INTO temporary (train_no) VALUES (
    ( /* ADDED */
        SELECT (train.col_train-ideal.col_ideal)*(train.col_train-ideal.col_ideal) 
        FROM train INNER JOIN ideal ON train.x=ideal.x
    ) /* ADDED */
)
> Affected rows: 1
> Time: 0.084s

与(不带括号)相反:-

INSERT INTO temporary (train_no) VALUES (
    /*(*/ /* ADDED */
        SELECT (train.col_train-ideal.col_ideal)*(train.col_train-ideal.col_ideal) 
        FROM train INNER JOIN ideal ON train.x=ideal.x
    /*)*/ /* ADDED */
)
> near "SELECT": syntax error
> Time: 0s

相关问题