-- 客户账户-商户层级:账户(结算主体)下挂多个商户(配送点) ALTER TABLE customers ADD COLUMN IF NOT EXISTS parent_customer_code VARCHAR(50) REFERENCES customers(customer_code) ON DELETE SET NULL, ADD COLUMN IF NOT EXISTS customer_role VARCHAR(20); COMMENT ON COLUMN customers.parent_customer_code IS '上级账户客户编码;商户指向账户'; COMMENT ON COLUMN customers.customer_role IS 'account=账户(结算主体), merchant=商户(配送点)'; CREATE INDEX IF NOT EXISTS idx_customers_parent ON customers(parent_customer_code); CREATE INDEX IF NOT EXISTS idx_customers_role ON customers(customer_role); -- 账户不可挂上级 ALTER TABLE customers DROP CONSTRAINT IF EXISTS customers_account_no_parent; ALTER TABLE customers ADD CONSTRAINT customers_account_no_parent CHECK (customer_role IS DISTINCT FROM 'account' OR parent_customer_code IS NULL); -- 防止自引用 ALTER TABLE customers DROP CONSTRAINT IF EXISTS customers_no_self_parent; ALTER TABLE customers ADD CONSTRAINT customers_no_self_parent CHECK (parent_customer_code IS NULL OR parent_customer_code <> customer_code);