samedi 26 décembre 2020

MySQL select within if statement in procedure

I have to create a procedure that inserts a row with a foreign key. This key it's a random id from another table that satisfies a condition, if there's no row that satifies it, then it will be a random id from all the ids in the table.

For example I want to create a Person and I want to assing him a car. I want his car to be a random choice from an specific color, but if there's no car from that color, then just choose a random car.

Here is my adapted current code:

DELIMITER //
DROP PROCEDURE IF EXISTS `test`;
CREATE PROCEDURE `test`( `id_color` INT )
BEGIN
    # I have auto increment id    
    INSERT INTO persons(id_color)
    VALUES ((
        SELECT IF((SELECT COUNT(*) FROM cars WHERE color = id_color) > 0, 
        SELECT car_id FROM cars WHERE color = id_color ORDER BY RAND() LIMIT 1,
        SELECT car_id FROM cars ORDER BY RAND() LIMIT 1)
    ));
    
END //
DELIMITER ; 

I am getting this error: '2014 Commands out of sync; you can't run this command now'

Don't know if it's possible to do it like that.

I use delimiter because I have to add more stuff.




Aucun commentaire:

Enregistrer un commentaire