如果值不同,如何插入或更新?

uyto3xhc  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(602)

我正在尝试编写一个sql查询,当它更新另一列时,该查询会将值设置为1。
具体来说,如果相应的哈希列被更改,我想将我的is\u patch\u file设置为1。如果哈希列没有更改,它应该保留当前存储的值。
这可能吗?
表结构

DROP TABLE IF EXISTS `program_files`;
CREATE TABLE `program_files` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `folder_id` int(10) unsigned NOT NULL,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `path` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `hash` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `is_patch_file` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_file` (`folder_id`,`name`,`path`,`hash`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

sql查询

INSERT INTO program_files (folder_id, name, path, hash, is_patch_file, enabled, created_at, updated_at) VALUES (3, 'TestName', 'TestPath', 'TestHash', 0, 1, NOW(), NOW()) ON DUPLICATE KEY UPDATE 
is_patch_file=1, #Is Patch file should ONLY be 1 if the hash is different from the original hash...otherwise keep our current value how do I do this?
hash=VALUES(hash),
updated_at=VALUES(updated_at);

INSERT INTO program_files (folder_id, name, path, hash, is_patch_file, enabled, created_at, updated_at) VALUES (3, 'TestName', 'TestPath', 'TestHash2', 0, 1, NOW(), NOW()) ON DUPLICATE KEY UPDATE 
is_patch_file=1, #Is Patch file should ONLY be 1 if the hash is different from the original hash...otherwise keep our current value how do I do this?
hash=VALUES(hash),
updated_at=VALUES(updated_at);
ds97pgxw

ds97pgxw1#

你可以比较一下 hashVALUES(hash) 在更新之前,在设置 is_patch_file .

ON DUPLICATE KEY UPDATE 
    is_patch_file = hash != VALUES(hash), 
    hash = VALUES(hash), 
    updated_at = VALUES(updated_at)

相关问题