跨多个表的差异列表与 INTERSECT

Difference list vs INTERSECT across multiple tables

对于给定的数据库数据结构:

Table      Attribute       Type                       Glossary

Species    Sp_name         C(10) P.K.                 Species name
           sp_woodtype     C(10)                      Wood Yielded by tree
           sp_maxht        I                          Max.height


Forest     Fo_name         C(10) P.K.                 Forest name
           Fo_size         I                          Forest area
           Fo loc          C(10)                      Geographical name
           Fo_comp         C(10)                      Forest owner


Tree       Tr_species      C(10) F.K. species.sp_name
           Tr_forest       C(10) F.K. forest.fo_name
           Tr_numb         I     P.K.                 Sequence number
           Tr_planted      Date                       Date of planting
           Tr_loc          C(10)                      Forest quadrant
           Tr_parent       I     F.K. tree.tr_numb    Procreating tree reference


Measure    Me_trnumb       I     F.K. tree.tr_numb
           Me_numb         I     P.K.                 Sequence number
           Me_result       I                          Test's measure
           Me_date         Date                       Measure taken on 
           Me_type         C(10)                      Type of measure

P.K。是主键,F.K。是外键,C(N)字符(N)类型,I Integer类型

我需要select所有森林中都有哪些树种,所以我尝试了以下方法,但似乎不对:

SELECT fo_name.forest, sp_name.species
FROM forest, species;

SELECT tr_species.tree, tr_forest.tree
FROM tree;

SELECT fo_name.forest, sp_name.species
FROM forest, species
INTERSECT
SELECT tr_species.tree, tr_forest.tree
FROM tree;

对于解决这个问题,差异列表是否比 INTERSECT 更好?

是关系除法的特例
您可以将每棵树的不同森林数与森林总数进行比较以找出:

SELECT tr_species
FROM   tree
GROUP  BY tr_species
HAVING count(DISTINCT tr_forest) = (SELECT count(*) FROM forest);

如果您需要的不仅仅是 PK,请将结果加入 table species

顺便说一句,数据类型character(10)不好,尤其不作为PK列。

  • Any downsides of using data type "text" for storing strings?