SQL。如何检查插入的数据是否包含来自另一个 table 的正确组的值?

SQL. How to check if inserted data contains value of correct group from another table?

如果有两个通用的类字典table。一个由类别组成,另一个由类别项目组成。我还有一个特定的 table 必须与适当类别的类别项目之一相关。这是示例:

类别table

id | title
-------------------
0  | payment type
1  | vehicle type

分类项目table

id | title      | category_id
-----------------------------
0  | hourly     | 0
1  | full time  | 0
2  | motorcycle | 1
3  | bus        | 1

员工人数table

id | name | payment_type 
------------------------
0  | Mike | 1
1  | Josh | 0
2  | Anna | 1

所以我需要员工table的专栏payment_type可能只有那些ids from Categories items table 属于 payment type from Categories table

我如何在 Postgres 中执行此操作?如果可能的话,我怎么能使用 typeorm 来做到这一点?

对于这种情况,简单的约束是不够的。我认为您将不得不使用 functiontrigger。看看@下面的文章:when-validation-is-not-enough-postgresql-triggers-for-data-integrity

我修改了示例,并编写了以下内容。

  CREATE FUNCTION validate_payment_type() returns trigger as $$
      DECLARE
        categoryid int;
      BEGIN
         categoryid := (select id from categories c inner join categories_items ci on c.id = c.category_id
         where NEW.payment_type = c.id);

        -- categoryid with zero is payment
        IF (categoryid != 0) THEN
          RAISE EXCEPTION 'Attempting to insert payment_type that has a category item that is not payment_type';
        END IF;
        RETURN NEW;
      END;
      $$ language plpgsql;

      CREATE TRIGGER validate_payment_type  BEFORE INSERT OR UPDATE ON Employees
      FOR EACH ROW EXECUTE PROCEDURE validate_payment_type();

注意:我没有在实时数据库上测试过,所以可能会有一些错别字。 注 2:您可以从 categoryId 更改为 categoryTitle,但您需要稍微更改查询,如果是 int,则使用 varchar 代替。