是否可以在没有表的select语句中创建许多行?

时间:2015-04-16 17:19:10

标签: mysql sql select

我想知道是否可以在此select语句中生成多于一行:

select
      floor(1+(rand()*(1+100-1))) as B1
     ,floor(1+(rand()*(1+100-1))) as B2
     ,floor(1+(rand()*(1+100-1))) as B3
     ,floor(1+(rand()*(1+100-1))) as B4
     ,floor(1+(rand()*(1+100-1))) as B5
     ,floor(1+(rand()*(1+100-1))) as B6 ;

而不是这(单行)

    B1  B2  B3  B4  B5  B6
    -- --   --  --  --  --
    48  35  30  44  31  24

我想看到这个(或者在循环中或者在循环中我想要的很多行)

B1  B2  B3  B4  B5  B6
-- --   --  --  --  --
48  35  30  44  31  24
24  2   34  15  22  15
11  7   2   36  27  26
49  19  44  17  49  47
39  4   48  32  16  34
23  10  32  29  48  9
45  49  13  17  45  25
38  16  15  25  33  41

如果有人知道在没有创建程序的情况下是否可以这样做,我将不胜感激!

2 个答案:

答案 0 :(得分:5)

大多数数据库提供了一种生成1..n行数据的方法(参见:SQL SELECT to get the first N positive integers),但MySQL并不容易。如果您有一个表,您知道有足够的行来满足您的要求,您可以使用它作为查询的基础,以获得您想要的。

例如,这将为您提供10行:

SELECT @N := @N +1 AS rownumber
     ,floor(1+(rand()*(1+100-1))) as B1
     ,floor(1+(rand()*(1+100-1))) as B2
     ,floor(1+(rand()*(1+100-1))) as B3
     ,floor(1+(rand()*(1+100-1))) as B4
     ,floor(1+(rand()*(1+100-1))) as B5
     ,floor(1+(rand()*(1+100-1))) as B6 
FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @N:=0) dummyRowNums LIMIT 10;

您可以使用任何表来实现此目标,只要您可以确定它的行数超过您希望达到的LIMIT。

如果您在结果集中不需要rownumber,则可以删除SELECT中的第一列并删除连接(",(SELECT @N:= 0)dummyRowNums" ):

SELECT floor(1+(rand()*(1+100-1))) as B1
     ,floor(1+(rand()*(1+100-1))) as B2
     ,floor(1+(rand()*(1+100-1))) as B3
     ,floor(1+(rand()*(1+100-1))) as B4
     ,floor(1+(rand()*(1+100-1))) as B5
     ,floor(1+(rand()*(1+100-1))) as B6 
FROM INFORMATION_SCHEMA.COLUMNS LIMIT 10;

答案 1 :(得分:1)

对于SQL Server,使用递归CTE ...并注意RAND函数的种子。

;With integers( num ) as
(
    Select 1 as num
        union all
    Select num + 1
        from integers
        where num <= 10
)
select
      num,
      floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B1
     ,floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B2
     ,floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B3
     ,floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B4
     ,floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B5
     ,floor(1+(rand(CHECKSUM(NEWID()))*(1+100-1))) as B6 
    from integers

有关RAND种子问题,请参阅此问题: RAND not different for every row in T-SQL UPDATE