Question

Hello i would like to add some rows from my pricelist table to products table. I am trying to fill my products table by testing data. Is possible to make query where i can add random amount of rows to my products table? The main problem is that i have more rows in select statement than in insert statement.

INSERT INTO products(product_name, product_price)
SELECT name_product, price_product, IF(RAND() > 0.2,1,0) AS random
FROM pricelist
HAVING random = 1
Was it helpful?

Solution

Put your condition in the WHERE clause. Your calculated column random does not makes sense since you don't to insert it on the other table.

INSERT INTO products(product_name, product_price)
SELECT name_product, price_product
FROM pricelist
WHERE RAND() > 0.2 = 1

OTHER TIPS

You mean you have more columns in select statement than in insert statement. The column number must match. There are also better ways to choose random rows...

INSERT INTO products(product_name, product_price)
SELECT name_product, price_product
FROM pricelist
ORDER BY RAND()
LIMIT 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top