gpt4 book ai didi

mysql - 插入一对一关系

转载 作者:可可西里 更新时间:2023-11-01 08:27:41 26 4
gpt4 key购买 nike

我的 MySQL 数据库包含两个表:usercoupon(一对一关系)。

我想选择所有没有优惠券的用户并创建一个新的(随机且唯一的)。

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)

最佳答案

假设您不介意从 6 继续向上获取下一个 coupon_id,这可以按如下方式完成(参见 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;

关于mysql - 插入一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com