2015-11-17 94 views
3

我的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)

+0

我有,你需要使用感受[INSERT ... SELECT](https://dev.mysql.com/doc/refman/5.6/en/insert-select.html)雖然我現在還沒有寫出模擬查詢的設置 –

+0

@ Memor-X謝謝你試圖幫助,但我還沒有想出如何使它工作。請您在有空的時候寫下;) –

+0

'SELECT u.is,u.name,COALESCE(u.coupon_id,LEFT(sha1(rand()),6))FROM user u LEFT JOIN coupon c on u.coupon_id = c.id'也許你想要這個查詢它不是很清楚 – Mihai

回答

2

假設你不介意從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; 
+0

令人驚歎!工作完美!謝謝。 –

+0

謝謝你讓我知道,很高興它幫助。 –

0

事情是這樣的,也許:

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

在此之後,您可以使用簡單的更新加入更新用戶表券。

+0

對不起,但我不明白你試圖解釋。運行這段代碼,我得到了'列計數與第1行的值計數不匹配'。 –

+0

我的代碼完全基於您提供的信息,未經測試。因此,如果優惠券表中還有其他列,您也必須將它們添加到select子句中。 – Harsh

+0

謝謝,現在它創建條目到'coupon'表中。但是我怎樣才能在'user'表中插入'coupon_id'? –

0
//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