【问题标题】:Generate value not in mysql table生成不在mysql表中的值
【发布时间】:2015-05-27 07:34:31
【问题描述】:

我使用了以下查询,用于生成不在 mysql 表中的随机值。

SELECT FLOOR( RAND()*1000 + 50 ) AS temp FROM tempcode WHERE  'temp' NOT IN ( SELECT code FROM tempcode ) LIMIT 1

但是当我使用运行不正常的虚拟数据将值减小到 RAND()*4 以检查目的时。

SELECT FLOOR( RAND()*1000 + 50 ) AS temp FROM tempcode WHERE  'temp' NOT IN ( SELECT code FROM tempcode ) LIMIT 1

原因是什么?有什么建议可以生成不在 mysql 表中的值吗?

【问题讨论】:

  • 因为您只生成从 0 到 3 的数字 - 没有太多随机性和很多冲突。也许UUID() 会满足您的需求。
  • @HoboSapiens 如何在 mysql 中使用 UUID()?如果所有数据都是随机生成的值,如果它已经在表中它应该返回null??
  • @phpPhil “尝试用反引号包裹 temp”是什么意思。可以发给我示例代码吗?
  • SELECT UUID() 可以。根据定义,UUID 应该是唯一的。
  • 没关系 - 我删除了评论,因为它不正确并且不能解决您的问题。这是基于'temp' 看起来不像正确的语法,但according to this 是。很抱歉造成混乱。

标签: mysql random unique floor


【解决方案1】:

这并不优雅,但它可以按要求工作,直到使用完所有 1000 个代码:

select x from  
    (select concat(hundreds, tens, ones) x from 
    (select 1 as ones union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) ones, 
    (select 1 as tens union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) tens, 
    (select 1 as hundreds union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) hundreds) thousand
    where thousand.x not in 
        (select code from tempcode) 
    order by rand() limit 1;

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 2021-02-14
    • 2013-12-02
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多