可用版本:Dev (3.21) | 最新 (3.20) | 3.19 | 3.18 | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11

外键

适用于 ✅ 开源版   ✅ 专业版   ✅ 企业版

外键是一种工具,通过保证被引用的值存在于父表中,可以进一步规范化您的数据库。在我们的示例数据库中,它强制执行BOOK.AUTHOR_ID引用的完整性。除了完整性之外,它还可以成为优化更复杂的执行计划的非常有用的工具,例如,支持JOIN消除。在 jOOQ 中,像这样创建外键

// Create a new table with columns and unnamed constraints
create.createTable("table")
      .column("column1", INTEGER)
      .constraints(
          foreignKey("column1").references("other_table", "other_column1")
      )
      .execute();

// Create a new table with columns and named constraints (recommended if you want to alter the constraint)
create.createTable("table")
      .column("column1", INTEGER)
      .constraints(
          constraint("fk").foreignKey("column1").references("other_table", "other_column1")
      )
      .execute();

jOOQ 的代码生成器将出于多种目的拾取外键,包括导航方法、ON KEY joins,最重要的是,功能非常强大的隐式 JOIN

方言支持

此示例使用 jOOQ

createTable("table")
      .column("column1", INTEGER)
      .constraints(
          constraint("fk").foreignKey("column1").references("other_table", "other_column1")
      )

翻译成以下特定方言的表达式

Access、DB2、Firebird、Hana、Teradata

CREATE TABLE table (
  column1 integer,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)

ASE、Sybase

CREATE TABLE table (
  column1 int NULL,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)

Aurora MySQL、Aurora Postgres、Derby、DuckDB、Exasol、H2、HSQLDB、MariaDB、MemSQL、MySQL、Postgres、Redshift、SQLServer、SQLite、Vertica、YugabyteDB

CREATE TABLE table (
  column1 int,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)

BigQuery

CREATE TABLE table (
  column1 int64,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1) NOT ENFORCED
)

ClickHouse

CREATE TABLE table (
  column1 Nullable(integer)
)
ENGINE Log()

CockroachDB

CREATE TABLE table (
  column1 int4,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)

Databricks

CREATE TABLE table (
  column1 int,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)
TBLPROPERTIES(
  'delta.columnMapping.mode' = 'name',
  'delta.feature.allowColumnDefaults' = 'supported'
)

Informix

CREATE TABLE table (
  column1 integer,
  FOREIGN KEY (column1) REFERENCES other_table (other_column1) CONSTRAINT fk
)

Oracle、Snowflake

CREATE TABLE table (
  column1 number(10),
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1)
)

SQLDataWarehouse

CREATE TABLE table (
  column1 int,
  CONSTRAINT fk FOREIGN KEY (column1) REFERENCES other_table (other_column1) NOT ENFORCED
)

Trino

CREATE TABLE table (
  column1 int
)
使用 jOOQ 3.21 生成。早期 jOOQ 版本的支持可能有所不同。 在我们的网站上翻译您自己的 SQL

反馈

您对此页面有任何反馈吗? 我们很乐意听取您的意见!

The jOOQ Logo