简体   繁体   English

MySQL select 在过程中的 if 语句中

[英]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.该键是另一个表中满足条件的随机 id,如果没有满足它的行,则它将是表中所有 id 中的随机 id。

For example I want to create a Person and I want to assing him a car.例如,我想创建一个 Person 并且我想为他分配一辆汽车。 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;我收到此错误:'2014 命令不同步; 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.我发现插入不涉及另一列,通常用于存储分配给汽车的人,这让我感到惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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