i have 4 tables products , orders, order_hist and order_prod_ref. data setup is provided below:
DROP TABLE products;
DROP TABLE orders;
DROP TABLE order_hist;
DROP TABLE ord_prd_ref;
create table products (product_id varchar2(20),FLG CHAR(1));
create table orders (order_id varchar2(20));
create table order_hist (order_id varchar2(20));
create table ord_prd_ref (product_id varchar2(20),order_id varchar2(20),prd_name varchar2(10));
INSERT INTO PRODUCTS values ('1000365007482','Y');
INSERT INTO PRODUCTS values ('1000359547456','N');
INSERT INTO PRODUCTS values ('1000359524206','N');
INSERT INTO PRODUCTS values ('1000082514435','N');
INSERT INTO PRODUCTS values ('1000088066693','N');
commit;
INSERT INTO ORDERS VALUES ('5000099148559');
INSERT INTO ORDERS VALUES ('5000099236099');
INSERT INTO ORDERS VALUES ('5000099705242');
INSERT INTO ORDERS VALUES ('5000002349523');
INSERT INTO ORDERS VALUES ('5000002349523');
INSERT INTO ORDERS VALUES ('5000099148559');
COMMIT;
INSERT INTO ord_prd_ref VALUES ('1000365007482','5000099148559','A');
INSERT INTO ord_prd_ref VALUES ('1000365007482','5000099148559','B');
INSERT INTO ord_prd_ref VALUES ('1000365007482','5000099148559','C');
INSERT INTO ord_prd_ref VALUES ('1000365007482','5000099148559','D');
INSERT INTO ord_prd_ref VALUES ('1000359547456','5000099236099','E');
INSERT INTO ord_prd_ref VALUES ('1000359547456','5000099236099','F');
INSERT INTO ord_prd_ref VALUES ('1000359547456','5000099236099','G');
INSERT INTO ord_prd_ref VALUES ('1000082514435','5000099705242','H');
INSERT INTO ord_prd_ref VALUES ('1000088066693','5000099236099','I');
INSERT INTO ord_prd_ref VALUES ('1000082514435','5000099705242','J');
INSERT INTO ord_prd_ref VALUES ('1000082514435','5000099705242','K');
COMMIT;
i want to insert data into order_hist from orders when products.flg='Y' and also delete that record from order table .
i tried this but its not giving me expected results as there is only one product_id with flg='Y' i.e 1000365007482
INSERT INTO order_hist
select * FROM orders a
WHERE
EXISTS (
SELECT
NULL
FROM
products,
ord_prd_ref,
orders
WHERE
products.product_id = ord_prd_ref.product_id
AND orders.order_id = ord_prd_ref.order_id
AND FLG = 'Y'
AND products.FLG = 'Y'
);
expected result should be the corresponding order_id should be inserted into order_hist table i.e 5000099148559.
select order_id from ord_prd_ref where product_id = '1000365007482';
any help is much appreciated.
Thanks in advance.