【问题标题】:SQL schema won't run with postgres?SQL 模式不会与 postgres 一起运行?
【发布时间】:2021-08-21 16:41:37
【问题描述】:

我想创建这个表架构

CREATE TABLE "CreatedAt" 
(
    "id" SERIAL PRIMARY KEY,
    "created" timestamptz NOT NULL DEFAULT (now()),
    "trafficData_id" int,
    "intersection_id" int
);

CREATE TABLE "Intersection" 
(
    "id" SERIAL PRIMARY KEY,
    "intersection_id" int,
    "site_no" int,
    "latitude" float8,
    "longitude" float8,
    "site_name" VARCHAR,
    "relationships" VARCHAR,
    "type" VARCHAR,
    "op_status" VARCHAR,
    "road_classification" VARCHAR,
    "road_geometry" VARCHAR,
    "road_layout" VARCHAR,
    "suburb" VARCHAR,
    "switch_on_date" timestamp
);

CREATE TABLE "trafficData" 
(
    "index" SERIAL PRIMARY KEY,
    "trafficData_id" int,
    "properties_id" int,
    "latest_stats" int,
    "name" VARCHAR,
    "length" int,
    "min_number_of_lanes" int8,
    "minimum_tt" int,
    "is_freeway" bool,
    "direction" VARCHAR
);

CREATE TABLE "PropertyReference" 
(
    "index" SERIAL PRIMARY KEY,
    "type_id" int,
    "name" VARCHAR,
    "href" VARCHAR,
    "id" int
);

CREATE TABLE "StatisticsTraffic" 
(
    "index" SERIAL PRIMARY KEY,
    "type_id" int,
    "intervalStart" timestamp,
    "travelTime" int,
    "delay" int,
    "speed" int,
    "excessDelay" int,
    "congestion" int,
    "score" int,
    "flowRestrictionScore" int,
    "averageDensity" int,
    "density" int,
    "enoughData" bool,
    "ignored" bool,
    "closed" bool
);

ALTER TABLE "Intersection" 
    ADD FOREIGN KEY ("intersection_id") REFERENCES "CreatedAt" ("intersection_id");

ALTER TABLE "trafficData" 
    ADD FOREIGN KEY ("trafficData_id") REFERENCES "CreatedAt" ("trafficData_id");

ALTER TABLE "PropertyReference" 
    ADD FOREIGN KEY ("type_id") REFERENCES "trafficData" ("properties_id");

ALTER TABLE "StatisticsTraffic" 
    ADD FOREIGN KEY ("type_id") REFERENCES "trafficData" ("latest_stats");

像这样。

现在由于某种原因,当我尝试将其迁移到数据库时出现此错误。

错误:迁移失败:第 0 行中引用表“CreatedAt”的给定键没有唯一约束匹配:CREATE TABLE“CreatedAt”(

我认为我没有正确设置主键或引用键。但是,有明确的外键,所以我不知道为什么它不能正确地将这些表连接在一起?

将 json 解组为的 golang 结构看起来像这样,我正在尝试考虑的表模式,以便将来可以添加不同的数据。

type trafficData struct {
        Href         string      `json:"href,omitempty"`
        ID           int         `json:"id,omitempty"`
        Name         string      `json:"name,omitempty"`
        PublicName   interface{} `json:"public_name,omitempty"`
        Organization struct {
            Href string `json:"href,omitempty"`
            ID   int    `json:"id,omitempty"`
        } `json:"organization,omitempty"`
        Origin struct {
            Href string `json:"href,omitempty"`
            ID   int    `json:"id,omitempty"`
        } `json:"origin,omitempty"`
        Destination struct {
            Href string `json:"href,omitempty"`
            ID   int    `json:"id,omitempty"`
        } `json:"destination,omitempty"`
        Enabled          bool        `json:"enabled,omitempty"`
        Length           int         `json:"length,omitempty"`
        MinNumberOfLanes int         `json:"min_number_of_lanes,omitempty"`
        MinimumTt        int         `json:"minimum_tt,omitempty"`
        IsFreeway        bool        `json:"is_freeway,omitempty"`
        Direction        string      `json:"direction,omitempty"`
        Coordinates      interface{} `json:"coordinates,omitempty"`
        LatestStats      struct {
            IntervalStart        time.Time `json:"interval_start,omitempty"`
            TravelTime           int       `json:"travel_time,omitempty"`
            Delay                int       `json:"delay,omitempty"`
            Speed                int       `json:"speed,omitempty"`
            ExcessDelay          int       `json:"excess_delay,omitempty"`
            Congestion           int       `json:"congestion,omitempty"`
            Score                int       `json:"score,omitempty"`
            FlowRestrictionScore int       `json:"flow_restriction_score,omitempty"`
            AverageDensity       int       `json:"average_density,omitempty"`
            Density              int       `json:"density,omitempty"`
            EnoughData           bool      `json:"enough_data,omitempty"`
            Ignored              bool      `json:"ignored,omitempty"`
            Closed               bool      `json:"closed,omitempty"`
        } `json:"latest_stats"`

        Trend                 interface{}   `json:"trend,omitempty"`
        Incidents             []interface{} `json:"incidents,omitempty"`
        LinkParams            interface{}   `json:"link_params,omitempty"`
        ExcludedSourceIDTypes interface{}   `json:"excluded_source_id_types,omitempty"`
        EmulatedTravelTime    interface{}   `json:"emulated_travel_time,omitempty"`
        ClosedOrIgnored       interface{}   `json:"closed_or_ignored,omitempty"`
    }

有什么想法吗?

###更新

这是一个更新,尝试加载脚本时仍然出现错误:D

CREATE TABLE createdAt (
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  trafficData_id int,
  intersection_id int,
);

CREATE TABLE Intersection (
  id SERIAL PRIMARY KEY,
  intersection_id int,
  site_no int,
  latitude float8,
  longitude float8,
  site_name VARCHAR,
  relationships VARCHAR,
  type VARCHAR,
  op_status VARCHAR,
  road_classification VARCHAR,
  road_geometry VARCHAR,
  road_layout VARCHAR,
  suburb VARCHAR,
  switch_on_date timestamp,
  CONSTRAINT fk_createdAt
      FOREIGN KEY(id) 
      REFERENCES createdAt(intersection_id)
);

CREATE TABLE trafficData (
  id SERIAL PRIMARY KEY,
  trafficData_id int ,
  properties_id int,
  latest_stats int ,
  name VARCHAR,
  length int,
  min_number_of_lanes int8,
  minimum_tt int,
  is_freeway bool,
  direction VARCHAR,
   CONSTRAINT fk_tdata_createdat
      FOREIGN KEY(id) 
      REFERENCES createdAt(intersection_id)
);

CREATE TABLE PropertyReference (
  id SERIAL PRIMARY KEY,
  type_id int,
  name VARCHAR,
  href VARCHAR,
  id int
  CONSTRAINT fk_tdata
      FOREIGN KEY(id) 
      REFERENCES trafficData(properties_id)
);

CREATE TABLE StatisticsTraffic (
  id SERIAL PRIMARY KEY,
  type_id int,
  intervalStart timestamp,
  travelTime int,
  delay int,
  speed int,
  excessDelay int,
  congestion int,
  score int,
  flowRestrictionScore int,
  averageDensity int,
  density int,
  enoughData bool,
  ignored bool,
  closed bool,
  CONSTRAINT fk_stats
      FOREIGN KEY(id) 
      REFERENCES trafficData(latest_stats)

);

【问题讨论】:

  • 引用的字段必须是唯一的。将unique 约束添加到引用的列(“CreatedAt”.intersection_id、“CreatedAt”.“trafficData_id”、“trafficData”.properties_id 和“trafficData”.latest_stats)。
  • 与你的问题无关,但在现代 Postgres 版本中,身份列是 recommended over serial,你真的应该 avoid those dreaded quoted identifiers。它们带来的麻烦远多于它们的价值。
  • 你的表 CreatedAt 应该代表什么?到目前为止,它看起来像一个实体,您可以在某个时间将 Intersection 与 trafficData 链接起来。是这样吗?那么为什么trafficData_idintersection_id 在该表中可以为空?同一张表是否在特定时间使用,但没有交叉路口或交通数据参考?
  • 最后你应该和你的命名保持一致。 trafficData 表中有一个列 properties_id。所以我推测这个链接指向一个properties 表并引用它的idproperties_id——不管你怎么称呼那个ID。但是没有properties 表。您真的想将一个 trafficData 行链接到(一组)属性还是一个属性?如果是后者,那么我会期望单数:property_id(将驻留在property 表中)。
  • 至于您的表PropertyReference:这包含一个index 作为标识列。我宁愿期望它被称为idPropertyReference_id,因为它标识一行。打电话给你的身份证。这是使用代理键时数据库中的通用命名约定。然后有一个type_id 但没有type 表。这是不好的。然后甚至还有一个id,但它不是表的ID。这是误导性的,因此非常糟糕。直截了当。

标签: sql postgresql go


【解决方案1】:

外键引用父表中的一行。为此,子表中的列链接到父表中在父表中唯一的列。因此,仅引用了一个父行。

CreatedAt 表中的行由列id(主键)唯一标识。但是您正在尝试创建引用列intersection_idtrafficData_id 的外键。这些不是唯一的,因此不能用作参考。

顺便说一句,你的桌子看起来很奇怪。您的表 Intersection 有一个列 id 和一个列 intersection_id。这是为什么?路口 ID 和路口 ID 有什么区别?

桥接表CreatedAt 不应该对其父表有外键,显然是IntersectiontrafficData,而不是相反?

这在我看来完全不对。

【讨论】:

  • 所以在上面添加了golang的struct来展示数据结构。我想这样做,以便架构将来可以接收不同的数据集,从而创建一个链接到其他表的表。我还有一个单独的交集数据集,它与传入的数据集有点相关
  • 我没有 golang。我看到其中涉及 JSON,并且 JSON 不是表示数据库的合适方式,因为 JSON 是为树结构而不是关系网而制作的。就个人而言,我不喜欢他们尝试用 Java 等 3GL 语言在树结构中投影数据库,就像那些 OR 映射器通常做的那样。这往往会导致问题。我宁愿让 DBMS 保存我的数据,只处理我的应用程序中的查询结果,这些查询结果仅仅是二维表,因此很容易用任何传统编程语言处理。
  • 糟糕,错字。那当然是“我不知道 golang”,但我想你已经猜到了:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
相关资源
最近更新 更多