简体   繁体   中英

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.

You can do:

INSERT INTO persons(id_color)
SELECT car_id 
FROM cars 
ORDER BY (color = id_color) DESC, RAND() 
LIMIT 1

The first sort criteria prints cars that have the given color first, if any. The second criteria shuffles the groups.

I find it surprising that the insert does not involve another column, typically to store the person that car is assigned to.

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