gpt4 book ai didi

mysql - INSERT、UPDATE 或 DELETE 的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 00:49:52 25 4
gpt4 key购买 nike

asset_property 表:

| asset_id | property_id | property_value |
|:--------:|:-----------:|:---------------|
| 146 | 1 | 4G |
| 146 | 3 | 68723-239Gs |
| 147 | 1 | A7 |

这是我的查询:

INSERT INTO asset_property (asset_id, property_id, property_value)
VALUES
(146, 1, '4G'),
(146, 2, 'Black & Decker'),
(146, 3, ''),
ON DUPLICATE KEY
UPDATE property_value = VALUES(property_value);

有没有办法这样说:

INSERT INTO asset_property (asset_id, property_id, property_value)
VALUES
(146, 1, '4G'),
(146, 2, 'Black & Decker'),
(146, 3, ''),
ON DUPLICATE KEY
UPDATE property_value = VALUES(property_value)
ON VALUES(property_value) IS NULL
DELETE FROM asset_property
WHERE asset_id = VALUES(asset_id)
AND property_id = VALUES(property_id);

或者我可以使用 PHP 来确定空的 property_value 集并构建第二个查询。所以我需要这个:

DELETE FROM asset_property
WHERE 'PRIMARY KEY' IN ('146-3');

语法没问题,但有 0 行受到影响。

我已经试过了:

SELECT 'PRIMARY KEY' FROM asset_property WHERE asset_id = 146;

但结果是:

| PRIMARY KEY |
|:------------|
| PRIMARY KEY |
| PRIMARY KEY |

MySQL Manual接缝说你不能。

最佳答案

DELETE FROM asset_property
WHERE 'PRIMARY KEY' IN ('146-3');

The syntax is okay, but 0 rows are affected.

没有任何语法错误,但这并不意味着它没问题 :) @rodrigoap 已经解释了那是什么意思,以及为什么 0 行匹配。

如果您需要删除与复合主键匹配的多条记录,您将不得不执行以下操作之一:

DELETE FROM asset_property
WHERE (asset_id = 146 AND property_id = 3)
OR (asset_id = 146 AND property_id = 7)
OR (asset_id = 146 AND property_id = 18)

或连接字段并测试:

DELETE FROM asset_property
WHERE CONCAT(asset_id, '-', property_id) in ('146-3', '146-7', '146-18')

(这个会比较慢,因为它不能利用任何索引)

或者只是在一个事务中执行多个删除语句:

BEGIN
DELETE FROM asset_property
WHERE asset_id = 146 AND property_id = 3
DELETE FROM asset_property
WHERE asset_id = 146 AND property_id = 7
DELETE FROM asset_property
WHERE asset_id = 146 AND property_id = 18
COMMIT

关于mysql - INSERT、UPDATE 或 DELETE 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9011217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com