【问题标题】:Inserting value in middle table in sqlite在sqlite的中间表中插入值
【发布时间】:2020-05-31 12:45:42
【问题描述】:

我正在尝试在中间表中插入一个值,该值是通过其他两个表的多对多关系创建的。所以这个中间表有 2 个外键(idProduct 和 idWarehouse),每个表一个外键和一个附加行(存储)。所以我在插入第三行时遇到了麻烦。 它给出了这个错误:

    Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) 
VALUES 
(SELECT

这是我的代码:

    INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) 
VALUES 
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas', 
'10')

【问题讨论】:

  • this answer。请注意,此类插入语句不使用VALUES,这可能是您的错误。答案与 db 无关,但 SQLite documentation 也是如此。
  • 我不明白,在您提供的链接中,他们也使用 VALUES 并将 SEARCH 查询放在括号中。

标签: java sqlite foreign-keys syntax-error


【解决方案1】:

每个查询都必须用括号括起来:

INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES 
(
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'), 
  '10'
);

如果这些查询始终只返回 1 行,这将起作用,因此 nameProductnameWarehouse 两列必须是唯一的。
该语句也可以不用VALUES 子句,用SELECT

INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) 
SELECT
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'), 
  '10';

【讨论】:

  • 是的,就是这样 :) 非常感谢!
猜你喜欢
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多