douhuan1979 2012-12-02 23:59 采纳率: 100%
浏览 53

使用随机的2个字符串命名表中的每一行

I want to choose a simple naming conventions to the table in my database.

It means I have to name each row with a random 2 word string.

For example

ID NAME

1 ROMEL SUMPI

2 BORMI SUIEMOD

and so on,,,,,,,,,

It means each NAME column should have a Unique name.....

How can I do this in PHP which uses postgreSQL DB....

Thank you in advance,,.,,,,

  • 写回答

2条回答 默认 最新

  • duanqi5114 2012-12-03 00:06
    关注

    I suspect you actually mean "arbitrary" unique names. Simple way could be:

    INSERT INTO tbl (id, name)
    SELECT g, 'name'::text || g || ' surname' || g
    FROM   generate_series(1, 1000) g;
    

    .. to generate 1000 distinct names - not random at all, but unique.

    To generate 100 names consisting of two words with 3 - 10 random letters from A-Z:

    INSERT INTO tbl (id, name)
    SELECT g%100
          ,left(string_agg(chr(65 + (random() * 25)::int), ''), 3 + (random() * 7)::int)
           || ' ' ||
           left(string_agg(chr(65 + (random() * 25)::int), ''), 3 + (random() * 7)::int)
    FROM   generate_series(1, 1000) g
    GROUP  BY 1
    ORDER  BY 1;
    

    ASCII code of 'A' is 65, the one of 'Z' is 90. Fortunately, the range between spans the basic upper case alphabet. You can find out with the ascii() function, which is the reverse of chr():

    SELECT ascii('A')
    

    The second method doesn't guarantee uniqueness, but duplicates are extremely unlikely with just a few hundred names. Eliminating possible duplicates is trivial. Add another SELECT layer where you GROUP BY name and pick min(id).

    评论

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。