使用PHP生成随机数据库插入

时间:2013-07-17 17:06:30

标签: php mysql random

我有两个看起来像这样的表:

表:矩阵

    matrix_id      round_id    p_1_1     p_1_2     p_2_1     p_2_2     p_3_1     p_3_2
    INT(11)        INT(11)    INT(11)   INT(11)   INT(11)   INT(11)   INT(11)   INT(11)
   AUTOINCREMENT

表:matrix_elements:

element_id       matrix
 INT(11)         INT(11)
AUTOINCREMENT

现在我需要从表matrix_elementsINSERT中随机选择一个新行到表matrix中。 p_1_1,p_1_2等中的每一个都必须使用matrix表中的随机matrix_elements填充。

唯一的要求是,p_1_1等列中的每两列都必须使用以下值填充:8

我完全迷失了,在你问之前我没有尝试过任何事情。 我只是需要一些好的方向来实现这一目标,而不是必须准备好的代码。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

这需要多个语句来做一行......我可能误解了你的要求,但是这里有:

编辑:修改为一个语句并实际使用RAND()

INSERT INTO matrix
SELECT
  NULL,
  1, -- NO idea what round_id should be...
  IF( 0 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1)),
  IF( 1 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1)),
  IF( 2 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1)),
  IF( 3 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1)),
  IF( 4 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1)),
  IF( 5 in (one8, two8), 8, (SELECT element_id 
                             FROM matrix_elements ORDER BY RAND() LIMIT 1))
FROM (
  SELECT
    one8,
    IF( one8 = two8, two8 + 1, two8 ) as two8
    FROM (
      SELECT
        FLOOR(RAND() * 6) AS one8,
        FLOOR(RAND() * 5) AS two8
    ) AS a
) AS b;