我有很多已编码的数据,我正在尝试制作查找表来添加代码的描述。如果设置了主键和外键,是否可以让查询自动返回查找表描述,或者您总是必须在查询中使用联接?这是我现在用来测试第一个查找表的两个表。
Table "public.severity_lookup"
Column | Type | Collation | Nullable | Default
---------------+-----------------------+-----------+----------+---------
severity | character varying(1) | | not null |
severity_desc | character varying(30) | | |
Indexes:
"pk_severity_lookup" PRIMARY KEY, btree (severity)
Referenced by:
TABLE "crashes" CONSTRAINT "fk_crashes_severity" FOREIGN KEY (severity) REFERENCES severity_lookup(severity)
Table "public.crashes"
Column | Type | Collation | Nullable | Default
---------------------------+------------------------+-----------+----------+---------
crash_id | character varying(31) | | |
...
severity | character varying(1) | | |
Foreign-key constraints:
"fk_crashes_severity" FOREIGN KEY (severity) REFERENCES severity_lookup(severity)
(我缩写了崩溃表,因为它很长)
Here is the data in the severity_lookup table:
SELECT * FROM severity_lookup;
severity | severity_desc
----------+----------------------
F | Fatality
I | Injury
P | Property Damage Only
(3 rows)
也许我想做的事情是不可能的,但我一直在四处寻找,但没有找到任何关于它的好信息。如果有人知道有关 SQL/postgres 中查找表的资源/教程,我将不胜感激。
对于上面的以下问题,为了能够查找两个表的数据,您可以创建连接两个表并返回描述和编码数据的视图,创建视图的示例查询如下:
CREATE VIEW crashes_with_descriptions AS
SELECT c.crash_id, c.severity, sl.severity_desc
FROM crashes c
JOIN severity_lookup sl ON c.severity = sl.severity;
创建视图后,您可以使用以下命令查询上述视图:
SELECT * FROM crashes_with_descriptions;
上面的查询将返回包含 crash_id、严重性和严重性_desc 的结果集。