Unique Foreign Key One To One
Add UNIQUE to the referencing column so a foreign key allows at most one child per parent, turning a one-to-many relationship into a true one-to-one.
Code
-- 一对一 = FOREIGN KEY + 被引用列 UNIQUE:同一父行最多被子表引用一次
CREATE TABLE companies (
id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE tax_profiles (
id integer PRIMARY KEY,
company_id integer NOT NULL UNIQUE,
vat_number text NOT NULL,
FOREIGN KEY (company_id) REFERENCES companies (id)
);
INSERT INTO companies (id, name) VALUES (1, 'acme'), (2, 'globex');
INSERT INTO tax_profiles (id, company_id, vat_number)
VALUES (1, 1, 'DE811');
-- 第二份档案再指向公司 1:外键本身满足,但 UNIQUE 先拦下
-- ERROR: duplicate key value violates unique constraint "tax_profiles_company_id_key"
-- INSERT INTO tax_profiles (id, company_id, vat_number) VALUES (2, 1, 'DE999');
-- company_id 上有唯一索引:从任一方向关联都是至多一行
SELECT c.name, t.vat_number
FROM companies c
LEFT JOIN tax_profiles t ON t.company_id = c.id
ORDER BY c.id;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with companies and tax_profiles among the objects involved.
The SQL constructs in play: one JOIN combining rows across tables; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a foreign-key REFERENCES clause that anchors each child row to its parent.
Applying it
Run it in the companies database context.
Statements that matter
SELECT c.name, t.vat_number
FROM companies c
LEFT JOIN tax_profiles t ON t.company_id = c.id
ORDER BY c.id;
CREATE TABLE tax_profiles (
id integer PRIMARY KEY,
company_id integer NOT NULL UNIQUE,
vat_number text NOT NULL,
FOREIGN KEY (company_id) REFERENCES companies (id)
);
INSERT INTO tax_profiles (id, company_id, vat_number)
VALUES (1, 1, 'DE811');
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- The references are `companies`, `tax_profiles`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.