[英]Insert into One-to-One Relationship
我的MySQL數據庫包含兩個表: user
和coupon
(一對一的關系)。
我想選擇所有沒有優惠券的用戶並創建一個新的(隨機且唯一的)。
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
快捷鍵:
選擇沒有優惠券的所有用戶: SELECT * from user WHERE coupon_id IS NULL;
生成一個隨機的6個字符串(MySQL): LEFT(sha1(rand()), 6)
。
假設你不介意從下一個coupon_id
繼續向上6,這可以按如下方式完成(參見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;
這樣的事情可能是:
Insert into coupon
select distinct id,LEFT(sha1(rand()), 6)
from user WHERE coupon_id IS NULL
在此之后,您可以使用簡單的連接更新來更新用戶表中的優惠券。
//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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.