所以我试图通过随机选择产品表中的id x时间来填充连接两个不同表的表,然后将此id与商店表的id一起放入。然后从shopa表中为所有id重复此操作。这样每家商店都会获得随机数量的产品;但是,因为有时候我随机选择的ID与表中已经存在的ID相同,例如
shop = 1 || product = 34
shop = 1 ||产品= 20
shop = 1 ||产品= 34
如何防止这种情况发生我正在尝试执行的代码
create or replace PROCEDURE GENERATEPRODUCTS
AS
PRODUCTTEMP NUMBER;
NROFPRODUCTS NUMBER;--total number of available products
NROFWINKELS NUMBER;--total number of shops
MAXNROFPRODUCT NUMBER;-- the maximum amount of products to be inserted
PRODUCTPERCENTAGEZONDER NUMBER;-- random percentage that will be added to 90%
PRODUCTPERCENTAGEMET NUMBER;-- total percentage of to be inserted products
WINKELS NUMBER;--counter for looping through shops
PRODUCTIDTEMP NUMBER;--the id of the product that needs to be inserted
BEGIN
PRODUCTIDTEMP :=1;
WINKELS := 1;
PRODUCTPERCENTAGEMET :=0;
PRODUCTPERCENTAGEZONDER := 0;
select count(ID)
into NROFWINKELS
FROM WINKEL;
select count(ID)
into NrofWinkels
FROM WINKEL;
select count(ID)
into NROFPRODUCTS
FROM PRODUCT;
select DBMS_RANDOM.VALUE(0,10) into PRODUCTPERCENTAGEZONDER FROM DUAL;
PRODUCTPERCENTAGEMET := (90+PRODUCTPERCENTAGEZONDER)*.010;
MAXNROFPRODUCT:=ROUND(NROFPRODUCTS*PRODUCTPERCENTAGEMET);
WHILE WINKELS <= NROFWINKELS
LOOP
WHILE MAXNROFPRODUCT<=NROFPRODUCTS
LOOP
SELECT ID
INTO PRODUCTTEMP
FROM(
SELECT ID
FROM PRODUCT
ORDER BY DBMS_RANDOM.VALUE)
WHERE ROWNUM=1;
INSERT INTO WINKEL_COUPON
("ID",WINKEL_ID,COUPON_ID)
VALUES
(PRODUCTIDTEMP,WINKELS,PRODUCTTEMP);
PRODUCTIDTEMP := PRODUCTIDTEMP+1;
END LOOP;
WINKELS := WINKELS+1;
END LOOP;
END;
在此代码中,我希望每家商店至少获得90%的可用产品;
答案 0 :(得分:0)
我认为你必须把CONSTRAINT放在桌子上。
通过这种方式,您可以确保某些列具有唯一值。 例如,如果您希望ColumnShop和ColumnProduct的值在表中是唯一的,则必须在表上放置一个看起来像这样的约束:
CONSTRAINT <NameTheConstraint> PRIMARY KEY(Shop, Product)
通过执行此操作,该表将仅接受要在表中插入的唯一值。 因此Shop = 1,如果该组合尚未存在,则将插入Product = 34。如果是这样,它将自动地引发一个违反约束的错误。