SQL条件INSERT

时间:2017-03-22 20:56:09

标签: mysql sql conditional sql-insert

我正在使用MySQL。如何在验证相关数据的基础上执行INSERT?原谅人为的例子。

如果我的表是:

> SELECT * FROM colors;
id color  owner
-- ------ -----
10 red    2
11 banana 6
12 blue   9

> SELECT * FROM fruit;
id  color_id  name
--  --------  -------
59  10        cherry
60  12        blueberry

其中fruit.color是colors.id的外键。

我想插入有关香蕉的信息,但前提是颜色的所有者是6.这里是原始INSERT:

INSERT INTO
    fruit
    (color_id, name)
VALUES
    (11, 'banana');

我想做类似的事情:

INSERT INTO
    fruit
    (color_id, name)
VALUES
    (11, 'banana')

-- ??? I have no idea what to put here ???
ONLY IF (
    (SELECT COUNT(*) FROM fruit
    INNER JOIN colors ON fruit.color_id = colors.id
    AND   colors.id     = 11
    WHERE colors.owners = 6) >= 1
)

最后一句显然不是真的,但我不知道该怎么做。如果尝试插入的owner我的color_id列等于我提供的值,则只会插入值。

帮助?

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

insert into fruit (color_id, name)
select 11, 'banana'
where (select count(*) from fruit join colors on fruit.color_id = colors.id
where colors.id = 11 and colors.owner = 6) >= 1;

或等效

insert into fruit (color_id, name)
select 11, 'banana'
where exists 
(select * from fruit join colors on fruit.color_id = colors.id
where colors.id = 11 and colors.owner = 6);

答案 1 :(得分:0)

这对你有用吗?

IF (SELECT COUNT(*) FROM fruit
    INNER JOIN colors ON fruit.color_id = colors.id
    AND   colors.id     = 11
    WHERE colors.owners = 6) >= 1
THEN
   INSERT INTO fruit
   (color_id, name)
   VALUES
   (11, 'banana');
END IF;