【问题标题】:MySQL: using random function in existing table for generating derived columnMySQL:在现有表中使用随机函数生成派生列
【发布时间】:2020-05-28 16:26:37
【问题描述】:

我有一个表“产品”,其中包含“类别”列,其中包含 10 个不同的类别,没有列 category_id。我想为每个类别派生一个包含新列 category_id 的表。

select product_id,description,category, round(rand(10)) as category_id from product;
select product_id,description,category, rand( over partition by 10) from product; 

使用上面的查询,我尝试过“round(rand())”,但是这只给出了 0 和 1,但我希望它为从 1 到 10 的 10 个产品分配 category_id。

我还想从两个随机类别中检索产品

【问题讨论】:

    标签: mysql mysql-workbench


    【解决方案1】:

    使用 FLOOR(1+ rand() * 10) 这会给你一个介于 1 和 10 之间的数字

    select product_id,description,category,FLOOR(1+ rand() * 10) as category_id from product;
    

    【讨论】:

    • 感谢您的快速更新,但它仍然不会创建唯一编号,我可以看到相同的编号重复。 select product_id,description,category,FLOOR(1+ rand() * 10) as category_id from product group by category; 在每个类别下我都有很多产品。目标是检索任何随机类别中列出的产品组
    • 显示一些数据和想要的结果,上面的代码生成1到10之间的随机数。随机还包括数字会重复。
    • 使用的查询:select product_id,description,category, FLOOR(1+ rand() * 10) as category_id from product group by category; 输出:product_id, Description, category, category_id 1 饼干烘焙食品 4 11 可乐饮料 1 18 Ariel 清洁产品 3 25 烧烤酱 调味品/酱料 2 预期输出如下: product_id, description, category, category_id 1 饼干烘焙食品 c1 11 可乐饮料 c2 18 Ariel 清洁产品 c3 25 烧烤酱调味品/酱汁 c4
    • 请编辑您的帖子,不仅要添加结果,还要添加结果的来源
    • 谢谢,我得到了正确的查询,下面的查询按照我的预期工作,我使用 MySQL 工作台工作。解决方案:select p.product_id, p.description,p.category from product p join (select c.product_id,c.category from product c order by rand() limit 2) cc on cc.category=p.category;
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多