create table SALES_BILL_VOUCHER
(
    ID            int auto_increment
        primary key,
    CODE          varchar(255)  null,
    DESCRIPTION   text          null,
    EMPLOYEE_ID   int           null,
    MAKER_ID      int           null,
    MAKER_DATE    datetime      null,
    VERIFIER_ID   int           null,
    MODIFY_DATE   datetime      null,
    VERIFIER_DATE datetime      null,
    REF_ID        int default 0 not null,
    COMPANY_ID    int           null,
    constraint SALES_BILL_VOUCHER_COMPANY_ID_fk
        foreign key (COMPANY_ID) references COMPANY (ID)
            on delete set null,
    constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk
        foreign key (MAKER_ID) references EMPLOYEE (ID)
            on delete set null,
    constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk_2
        foreign key (VERIFIER_ID) references EMPLOYEE (ID)
            on delete set null,
    constraint SALES_BILL_VOUCHER_EMPLOYEE_ID_fk_3
        foreign key (EMPLOYEE_ID) references EMPLOYEE (ID)
            on delete set null
);

create table SALES_BILL_VOUCHER_ITEM
(
    ID           int auto_increment
        primary key,
    REF_ID       int    default 0 not null,
    VOUCHER_ID   int              null,
    INVENTORY_ID int              null,
    DESCRIPTION  text             null,
    QUANTITY     double default 0 not null,
    PRICE        double default 0 not null,
    constraint SALES_BILL_VOUCHER_ITEM_INVENTORY_ID_fk
        foreign key (INVENTORY_ID) references INVENTORY (ID)
            on delete set null,
    constraint SALES_BILL_VOUCHER_ITEM_SALES_BILL_VOUCHER_ID_fk
        foreign key (VOUCHER_ID) references SALES_BILL_VOUCHER (ID)
            on delete cascade
);


/**
  * 获取采购单的采购单
 */
select V.*
from PURCHASE_BILL_VOUCHER as V
         join (select distinct VI.VOUCHER_ID
               from PURCHASE_BILL_VOUCHER_ITEM as VI
                        left join PURCHASE_ORDER_ITEM as OI on VI.PURCHASE_ORDER_ITEM_ID = OI.ID
               where ORDER_ID = 159) as U on V.ID = U.VOUCHER_ID;
/**
  * 获取采购单的采购单
 */
select pbv1_0.ID,
       pbv1_0.CODE,
       pbv1_0.COMPANY_ID,
       pbv1_0.DESCRIPTION,
       pbv1_0.EMPLOYEE_ID,
       pbv1_0.INVOICE_ID,
       pbv1_0.MAKER_ID,
       pbv1_0.MAKER_DATE,
       pbv1_0.MODIFY_DATE,
       pbv1_0.REF_ID,
       pbv1_0.VERIFIER_ID,
       pbv1_0.VERIFIER_DATE
from PURCHASE_BILL_VOUCHER pbv1_0
where pbv1_0.ID in ((select distinct pbvi1_0.VOUCHER_ID
                     from PURCHASE_BILL_VOUCHER_ITEM pbvi1_0
                              left join PURCHASE_ORDER_ITEM oi1_0 on oi1_0.ID = pbvi1_0.PURCHASE_ORDER_ITEM_ID
                     where oi1_0.ORDER_ID = ?));
