如何为MySQL编写单个SQL语句来检查值,然后如果为true则执行INSERT?

时间:2013-12-09 16:05:15

标签: mysql sql select insert

我有以下声明:

SELECT pinpicsid
FROM user_collection
JOIN pin ON user_collection.pinid = pin.id
WHERE username = 'myuser'
AND pinpicsid = '98802';

如果它返回空白(或没有行),我想像这样执行INSERT:

SELECT id INTO @id FROM pin WHERE pinpicsid = '98802';

INSERT INTO user_collection (pinid, username)
VALUES (@id, 'ethanwa');

有没有办法将所有这些组合成一个单一的陈述?

1 个答案:

答案 0 :(得分:2)

为什么不只是INSERT ... SELECT?

INSERT INTO user_collection (pinid, username)
SELECT id, 'ethanwa' FROM pin WHERE pinpicsid = '98802';

此处的语法:http://dev.mysql.com/doc/refman/5.6/en/insert-select.html

如果您需要强制执行pinid的唯一性,但仍想更新用户名,则可以执行以下操作:

INSERT INTO user_collection (pinid, username)
SELECT id, 'ethanwa' FROM pin WHERE pinpicsid = '98802'
ON DUPLICATE KEY UPDATE username = VALUES(username)

如果不了解更多有关此脚本的目标,则很难更准确。