如果内部查询什么也找不到,请取消

时间:2013-01-28 19:51:53

标签: mysql insert

我收到了以下问题:

INSERT INTO contracts_settings (contract_id, setting_id, setting_value)
VALUES (:contract_id, (
    SELECT  setting_id
    FROM    settings
    WHERE   setting_type = :setting_type
        AND setting_name = :setting_name
    LIMIT   1
), :setting_value)
ON DUPLICATE KEY UPDATE setting_value = :setting_value

前缀为:的值将替换为使用PHP PDO::bindBalue的数据。

如果内部查询什么都找不到(它返回NULL),还要INSERT一个NULL语句。如何避免?

感谢。

1 个答案:

答案 0 :(得分:2)

INSERT ... VALUES语法转换为 INSERT ... SELECT

INSERT INTO contracts_settings 
  (contract_id, setting_id, setting_value)
SELECT 
    :contract_id,
    setting_id,
    :setting_value
FROM  settings
WHERE setting_type = :setting_type
  AND setting_name = :setting_name
LIMIT   1

ON DUPLICATE KEY UPDATE 
    setting_value = :setting_value ;