12

I have a test SQLite table:

CREATE TABLE test (
  id INTEGER PRIMARY KEY NOT NULL, 
  x REAL NOT NULL  DEFAULT (RANDOM()),
  y REAL NOT NULL  DEFAULT (RANDOM()),
  z REAL NOT NULL  DEFAULT (RANDOM())
)

and I want to create over thousands of rows of random data, and how can I do it using a SQL query? I can't use a SQL FOR loop because loops are not supported in SQLite, and I'm thinking of SELECTing all the data from the table then INSERT for each row, so the number of rows double each time I execute the query. I think that requires a nested query, which I don't understand.

4

6 回答 6

11

去hacky,这将一次插入多达2048个随机行,通过设置限制来决定多少;

INSERT INTO TEST (x,y,z)
  SELECT RANDOM(), RANDOM(), RANDOM()
   FROM (SELECT * FROM (
         (SELECT 0 UNION ALL SELECT 1) t2, 
         (SELECT 0 UNION ALL SELECT 1) t4,
         (SELECT 0 UNION ALL SELECT 1) t8,
         (SELECT 0 UNION ALL SELECT 1) t16,
         (SELECT 0 UNION ALL SELECT 1) t32,
         (SELECT 0 UNION ALL SELECT 1) t64,
         (SELECT 0 UNION ALL SELECT 1) t128,
         (SELECT 0 UNION ALL SELECT 1) t256,
         (SELECT 0 UNION ALL SELECT 1) t512,
         (SELECT 0 UNION ALL SELECT 1) t1024,
         (SELECT 0 UNION ALL SELECT 1) t2048
         )
    ) LIMIT 246;
于 2013-07-29T18:38:15.027 回答
7

您可以使用递归查询

此查询生成一个包含 1000 个随机数的表:

CREATE TABLE test(field1);

INSERT INTO test
  WITH RECURSIVE
    cte(x) AS (
       SELECT random()
       UNION ALL
       SELECT random()
         FROM cte
        LIMIT 1000
  )
SELECT x FROM cte;
于 2014-07-09T20:02:28.667 回答
2

我同意 Stenci,您可以使用递归查询。自2014 年 2 月 3 日 SQLite 3.8.3 版以来,增加了对 CTE 的支持。以下查询生成 OP 请求的包含 1000 个随机数的表:

CREATE TABLE test (
  id INTEGER PRIMARY KEY NOT NULL, 
  x REAL NOT NULL,
  y REAL NOT NULL,
  z REAL NOT NULL
);
INSERT INTO test
    WITH RECURSIVE
      cnt( id, x, y, z) AS (
      VALUES(1 , random(), random(), random()) UNION ALL 
      SELECT id+1,random(),random(), random() FROM cnt WHERE ID<1000)
    select * from cnt;
于 2015-01-25T18:28:40.867 回答
1

这似乎做你想做的事。您将不得不运行它几次,因为它每次都会使现有行数加倍。并且您需要至少有一行数据开始。

insert into test select random(), random(), random(), random() from test;

于 2013-07-29T18:28:56.660 回答
1

如果您在 sqlite3 shell 中,则可以使用generate_series()

insert into test (x,y,z) select random(), random(), random() from generate_series(1, 10000);

于 2021-01-24T22:35:07.803 回答
0

只需将函数 RANDOM() 和 ABS() 与操作 % (mod) 混合。

示例:插入从 0 到 10 的随机数

INSERT INTO test(field1) VALUES( abs(random() % 11) );
于 2013-11-07T13:00:33.413 回答