我收到了以下问题:
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语句。如何避免?
感谢。
答案 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 ;