简体   繁体   中英

Insert into One-to-One Relationship

My MySQL database contains two tables: user and coupon (one-to-one relationship).

I would like to select all users that do not have a coupon and create a new one (random and unique).

user TABLE:
___________________________________
|  id   |   name   |   coupon_id  |
-----------------------------------
   1        John         5
   2        Mary         (null)  // Need to create one coupon.
   3        Doe          2
   4        Max          (null)  // Need to create one coupon.
   5        Rex          1
   7        Bill         (null)  // Need to create one coupon.


coupon TABLE:
______________________________________________
|  id   |   code (random 6-chars - unique)   |
----------------------------------------------
   1        80k2ni
   2        0akdne
   5        nk03jd

Shortcuts:

Select all users without coupon: SELECT * from user WHERE coupon_id IS NULL;

Generate a random 6-chars string (MySQL): LEFT(sha1(rand()), 6) .

Assuming you don't mind continuing upwards from 6 for the next coupon_id , this can be done as follows (see SQL Fiddle Demo ):

-- Declare and set variables
SET @id_for_insert = (SELECT MAX(`id`) FROM `coupon`);
SET @id_for_update = @id_for_insert;

-- Insert new coupons
INSERT INTO `coupon` (id, code)
SELECT @id_for_insert := @id_for_insert + 1, LEFT(SHA1(RAND()), 6)
FROM `user`
WHERE coupon_id IS NULL;

-- Update users that don't already have a coupon with the newly created coupons
UPDATE `user`
SET coupon_id = @id_for_update := @id_for_update + 1
WHERE coupon_id IS NULL;

Something like this maybe:

Insert into coupon 
select distinct id,LEFT(sha1(rand()), 6) 
from user WHERE coupon_id IS NULL

After this, you can update coupon in user table using simple update with join.

//check if works inform me i will be glad
CREATE PROCEDURE `syncCouponUser` ()
BEGIN
  INSERT INTO coupon(id,code)//create coupons var no-used user ids
    select
    id,
    LEFT(sha1(rand())
    from user
    where coupon_id IS NULL ;

     UPDATE user //add coupons from coupon table with matches
    SET coupon_id=(
    select c.coupon_id
    from coupon c join user u 
    on c.id=u.id);

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM