简体   繁体   中英

MySQL: using random function in existing table for generating derived column

i have a table 'product' with column 'category' which consists of 10 different categories without a column category_id. i want to derive a table with new column category_id for each category.

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; 

using above query i have tried "round(rand())" however this gives only 0 and 1, but i want it to allocate category_id for 10 products from 1 to 10.

Also i want to retrieve the products from two random category

Use FLOOR(1+ rand() * 10) this will give you a number between 1 and 10

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM