【问题标题】:Unable to insert into table where column is a foreign key [duplicate]无法插入列是外键的表中[重复]
【发布时间】:2019-02-15 11:59:38
【问题描述】:

插入我的表格时出现此错误:

错误:关系“Item”的列“brandid”不存在

brandId 列上有一个外键约束,将其链接到另一个表的 id。

我插入的表是这样定义的:

Column  |  Type   |                      Modifiers                      | Storage  | Stats target | Description 
---------+---------+-----------------------------------------------------+----------+--------------+-------------
 id      | integer | not null default nextval('"Item_id_seq"'::regclass) | plain    |              | 
 name    | text    | not null                                            | extended |              | 
 price   | money   | not null                                            | plain    |              | 
 sizes   | json    | not null                                            | extended |              | 
 brandId | integer | not null                                            | plain    |              | 
 deptId  | integer | not null                                            | plain    |              | 
Indexes:
    "item_pk" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "Item_fk0" FOREIGN KEY ("brandId") REFERENCES "Brand"(id)
    "Item_fk1" FOREIGN KEY ("deptId") REFERENCES "Department"(id)

我正在尝试执行以下插入语句:

INSERT INTO "Item" (name, price, sizes, brandId, deptId) VALUES
        ('Air Force 1', '120.00', '{"12" : 1 , "10" : 12}',
            (SELECT id FROM "Brand" WHERE name= 'Nike'),
            (SELECT id FROM "Department" WHERE name= 'Mens Shoes'));

我数据库中的所有 id 列都是串行类型。

Brand 和 Department 表已经被填充,并且这些 select 语句已经过测试并且可以正常工作。

【问题讨论】:

  • 您的品牌表中是否有不止一只耐克品牌鞋?与系鞋相同的问题?我会将它们加载到一个变量中,看看你是否真的得到了标量结果。老实说,我从来没有尝试过这样的插入。不确定它是否会起作用,我会怀疑它的性能。

标签: sql postgresql quoted-identifier


【解决方案1】:

错误告诉你pgsql找不到字段brandid(而不是你预期的brandId)。区别是我与我。 尝试将字段名称放在双引号中的插入查询中

INSERT INTO "Item" (name, price, sizes, "brandId", "deptId") VALUES
    ('Air Force 1', '120.00', '{"12" : 1 , "10" : 12}',
        (SELECT id FROM "Brand" WHERE name= 'Nike'),
        (SELECT id FROM "Department" WHERE name= 'Mens Shoes'));

【讨论】:

  • 哇,谢谢!为什么我必须用“”而不是其他的来包装这两列?
  • 因为这两列名称中有大写字母。 PostgreSQL 将所有不被双引号括起来的 ddl 名称小写。这就是为什么在设计数据库时使用 camel_case 的良好约定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多