2013-04-05 97 views
0

我有一些电子商务网站的优惠券软件。我想一次生成一堆优惠券。它由2个表格组成。 1为优惠券,1为优惠券说明。主键是coupon_id。是这个正确的SQL?

这是做sql的正确方法吗? coupon_id会匹配吗?由于它是自动递增的,我不是输入一个数字,我认为它应该。

编辑:我只是复查,仅在优惠券表的coupon_id字段自动递增的不是一个在coupon_description

但我不知道,如果使用2个刀片是正确的方式。

INSERT INTO coupons (
    coupon_id, 
    coupon_type, 
    coupon_code, 
    coupon_amount, 
    coupon_minimum_order, 
    coupon_start_date, 
    coupon_expire_date, 
    uses_per_coupon, 
    uses_per_user, 
    restrict_to_products, 
    restrict_to_categories, 
    restrict_to_customers, 
    coupon_active, 
    date_created, 
    date_modified 
    ) 
    VALUES (
    '' , '', '" . substr(md5(uniqid(rand(), true)), 0, 8) ."', '100' , '1' , '06/05/2013' , '06/11/2013' , '1' , '1', '', '', '', '', '', '') 

    INSERT INTO coupons_description (
    coupon_id, 
    language_id, 
    coupon_name, 
    coupon_description 
    ) 

    VALUES (
    '', '1', 'test coupon', 'test' 

    ) 

回答

0

由于只有一个是自动递增的,所以我会先插入该表,然后查找该值并将其硬编码到从属表中。即:

INSERT INTO coupons (
coupon_type, 
coupon_code, 
...) 
VALUES ('', '" . substr(md5(uniqid(rand(), true)), 0, 8) ."', '100' ,...). 

请注意,coupon_id不在insert语句中。数据库将自己分配(假定自动增量正在做它应该做的)。一些数据库让你分配这个,但我认为这是一个糟糕的形式。那么问题就是再次找到该记录。我会用:

select * from coupons order by coupon_id desc; 

除非别人是在同一时间加入优惠券,你应该看到在上面的优惠券。如果您使用了唯一的优惠券名称或说明,这将有所帮助。无论如何,你必须采取分配的ID,然后更新表没有自动增量:

INSERT INTO coupons_description (
coupon_id, 
language_id, 
coupon_name, 
coupon_description) 

VALUES ('123', '1', 'test coupon', 'test') 

其中“123”是真的不管你coupon_id从select语句中。

但是你的语法看起来不错,否则。

+0

我走了这个,只是设置循环开始在我检查数据库中的最后一个值。不是这样做的最好方法。我认为这些表格可能应该结合起来,但我没有时间重新编写随附的代码。无论如何感谢您的帮助 – Sackling 2013-04-14 00:57:46

0

我可以去“消费券”,表检查最大coupon_id并明确指定插入新的ID。我认为这是防止任何不匹配的更安全的方法。

假设您已经有100张优惠券了。所以你的情况:

INSERT INTO coupons (
    coupon_id, 
    coupon_type, 
    ... 
) VALUES (101 , '', ...); 

INSERT INTO coupons_description (
    coupon_id, 
    language_id, 
    coupon_name, 
    coupon_description 
) VALUES (101, '1', 'test coupon', 'test') 
0

我建议要么合并这两个表(他们似乎有一个1:1的关系),或改变说明表,以便coupon_id是第一个表的外键和删除自动增量。之后,你可以插入到第一个表中,然后不用猜测要插入到第二个表中的id,你只需使用select @@ identity; (或选择scope_identity();如果在SQL服务器上)