2009-11-27 69 views
3

在postgres中有一個內置函數generate_series(),它可以生成帶有數字的行。用mysql生成很多行

有沒有在mysql中的函數做同樣的事情?

+0

太棒了:) 如果你發現一個重複的問題給你答案,我會建議關閉這一個。 – 2009-11-27 02:38:39

+0

我如何關閉一個問題?鏈接在哪裏?我想我可能沒有足夠的聲望去做。 – anru 2009-11-27 02:43:05

回答

3

如果一切都失敗了,你可以在MySQL的複製功能的過程。
像這樣的東西可能會奏效

DELIMITER // 
DROP PROCEDURE IF EXISTS `generate_series`// 
CREATE PROCEDURE `generete_series`(p_start Int, p_end Int) 
BEGIN 
    /* We need a temporary table to hold the values until we can output them */ 
    CREATE TEMPORARY TABLE `temp_series`(val Int Not Null); 

    /* Add all the values in the range to the temp table. */ 
    set @insert_query = CONCAT('INSERT INTO `temp_series` VALUES (', p_start, ')'); 
    set @ind = p_start + 1; 
    while @ind <= p_end do 
     set @insert_query = CONCAT(@insert_query, ',(', @ind, ')'); 
     set @ind = @ind + 1; 
    end while; 

    prepare stmt FROM @insert_query; 
    execute stmt; 

    /* Select the values and echo them back. */ 
    SELECT * FROM `temp_series`; 

    /* Free resources. This isnt needed, technically, unless 
    * you plan on using the function multiple times per connection */ 
    DROP TABLE `temp_series`; 
END// 
DELIMITER ; 

注意,這不是一個真正的非常有效的方法,因爲它使用一個臨時表,並準備查詢。經常使用不是一件好事。

你應該尋找替代方法。最有可能有更好的方式去做任何你想做的事情,而不必訴諸於此。