2012-11-05 34 views
0

我有一個查詢我需要運行,我有2個問題。如何生成隨機代碼,並多次運行sql

首先這裏是我的查詢:

INSERT INTO `anzie_oscommerce`.`discount_codes` (
`discount_codes_id` , 
`discount_description` , 
`products_id` , 
`categories_id` , 
`manufacturers_id` , 
`excluded_products_id` , 
`customers_id` , 
`orders_total` , 
`order_info` , 
`exclude_specials` , 
`discount_codes` , 
`discount_values` , 
`minimum_order_amount` , 
`expires_date` , 
`number_of_orders` , 
`number_of_use` , 
`number_of_products` , 
`status` 
) 
VALUES (
'' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' 
); 

第一個問題是我需要生成我正努力與uniqid功能我從PHP走上做隨機碼,但我知道這是不可能的。有沒有辦法在SQL中做類似的事情?

第二個問題是我需要運行這250次才能生成250個不同的折扣代碼。有多種方法可以多次運行sql嗎?

+0

你是在尋找一個隨機的ID或只是唯一的?也就是說,你是否擔心有人能夠從另一個代碼猜測代碼? – JohnFx

+0

我認爲隨機以及獨特。因爲你說的代碼不應該容易被猜到。我認爲我包含在sql語句中的php代碼完全是這樣。 – Sackling

回答

1

對於第一個問題:它取決於您使用的數據庫。 Mysql有一個rand()函數:https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

對於第二種情況:250對於數據庫來說並不是很多 - 只要把它放在一個php for循環中就可能會很好。

+0

我想我可以做到這一點。只是好奇沒有辦法直接從phpmyadmin做到這一點? – Sackling

+0

我最終這樣做了。非常簡單,我可以像以前一樣生成代碼,因爲它是一種php方法。謝謝。 – Sackling

+0

很高興幫助。我認爲重複執行此操作的唯一方法是將插入語句放入存儲過程中,並將其包裝在REPEAT(或其他類型的)循環中。 – sonofagun

0

我喜歡答案sonofagun答案。另一個訣竅是從一個虛擬表中選擇250次。

INSERT INTO `anzie_oscommerce`.`discount_codes` (
`discount_codes_id` , 
`discount_description` , 
`products_id` , 
`categories_id` , 
`manufacturers_id` , 
`excluded_products_id` , 
`customers_id` , 
`orders_total` , 
`order_info` , 
`exclude_specials` , 
`discount_codes` , 
`discount_values` , 
`minimum_order_amount` , 
`expires_date` , 
`number_of_orders` , 
`number_of_use` , 
`number_of_products` , 
`status` 
) 
(select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all 
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all 
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all 
select '' , 'GALA 2012', '' , '' , '' , '' , '' , '2', '1', '0', substr(md5(uniqid(rand(), true)), 0, 8), 250, '0.0000', '2013-22-06', '0', '1', '0', '1' union all 
...however many times 
);