我有一张如下所示的表格
mysql> desc cust_vend_relation ;
+-----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+--------------+------+-----+---------+----------------+
| customer_id | int(11) | YES | | NULL | |
| vendor_id | varchar(50) | YES | MUL | NULL | |
| address_label | varchar(50) | YES | | NULL | |
| vendor_name | varchar(50) | YES | | NULL | |
| cust_ven_id | int(11) | NO | PRI | NULL | auto_increment |
| city | varchar(50) | YES | | NULL | |
| ----------------------+--------------+------+-----+---------+----------------+
示例数据:
mysql> select customer_id , vendor_id , address_label , vendor_name ,cust_ven_id ,city from cust_vend_relation;
+-------------+------------+---------------+----------------+-------------+----------------+
| customer_id | vendor_id | address_label | vendor_name | cust_ven_id | city |
+-------------+------------+---------------+----------------+-------------+----------------+
| 267 | 5000821693 | Office | Imax Vendor 01 | 247 | Hyderabad |
| 266 | 5000821693 | office | Imax Vendor 01 | 256 | Hyderabad |
| 266 | 5000821693 | home | Imax Vendor 01 | 258 | Hyderabad |
| 266 | 5000821693 | ttttt | Imax Vendor 01 | 260 | Hyderabad |
| 272 | 5000821693 | home | Imax Vendor 01 | 261 | Hyderabad city |
| 270 | 5000821693 | Haii | Imax Vendor 01 | 262 | Hyderabad city |
+-------------+------------+---------------+----------------+-------------+----------------+
根据表结构,我没有任何主键,我可以依赖它来说明它是否重复(我可以说的唯一情况是 address_label 和 vendor_id 列可以重复)
请您告诉我如何在这种情况下使用插入或更新?
INSERT INTO cust_vend_relation (customer_id, vendor_id, address_label,vendor_name,city)
VALUES (267, 5000821693, 'office' , 'Imax Vendor 01' , 'Hyderabad') ON DUPLICATE KEY
答案 0 :(得分:1)
您可以使用两列唯一约束(address_label,vendor_id)...
你有cust_ven_id作为主键!
答案 1 :(得分:0)
根据您的示例数据,候选唯一键将是列customer_id, vendor_id, address_label
的三元组。如果这些列(或其他一些集合)确实保证是唯一的,那么在它们上创建一个唯一索引:
create unique index idx_ cust_vend_relation_3 on cust_vend_relation(customer_id, vendor_id, address_label);
然后,您可以将insert
表达为:
INSERT INTO cust_vend_relation (customer_id, vendor_id, address_label, vendor_name, city)
VALUES (267, 5000821693, 'office' , 'Imax Vendor 01' , 'Hyderabad')
ON DUPLICATE KEY
UPDATE vendor_name = VALUES(vendor_name),
city = VALUES(city);