对INSERT,UPDATE或DELETE的SQL查询

时间:2012-01-25 22:17:12

标签: mysql sql

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接缝说你不能。

3 个答案:

答案 0 :(得分:1)

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

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

没有任何语法错误,但这并不意味着它没关系:) @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')

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

或者只是在事务中执行多个delete语句:

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

答案 1 :(得分:0)

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

删除0行因为where子句为false,文本'PRIMARY KEY'不在列表中('146-3')。

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

这一个为表asset_property中的每一行返回文本'PRIMARY KEY',其中asset_id是146。

答案 2 :(得分:0)

那么,您的PRIMARY KEY是由asset_idproperty_id组成的?在这种情况下,你可以这样做DELETE

DELETE FROM asset_property
WHERE asset_id = 146 AND property_id = 3