如何使用复合主键进行删除

时间:2018-03-13 08:40:16

标签: mysql sql-update sql-delete composite-primary-key

我是数据库新手,我的问题是如何使用复合主键进行删除。这是我的表结构,

CREATE TABLE DevProj (
    DeveloperID int NOT NULL,
    ProjectID int NOT NULL,
    WorkDate Datetime,
    WorkingHours int,
    Overtime int,
    Descriptions varchar(255),
    Primary key(DeveloperID,ProjectID,WorkDate) 
);

insert into DevProj (DeveloperID,ProjectID,WorkDate,WorkingHours,Overtime,Descriptions) values
(1,2,'2018-1-1',10,5,'done all'),
(1,2,'2018-1-2',10,5,'done C++'),
(1,3,'2018-1-1',10,5,'done C#'),
(2,2,'2018-1-3',10,5,'done JAVA'),
(3,3,'2018-1-4',10,5,'done SQL');

假设我需要删除(1,2,'2018-1-1',10,5,'done all')此记录,我该怎么做,有复合priamry密钥,没有单独的列作为主要密钥删除,例如:Delete from devProj where id = 1。那么,我怎样才能为删除记录编写查询,我在更新时也遇到了这个问题。

2 个答案:

答案 0 :(得分:1)

如果要删除基于复合主键的记录,可以使用MySQL的简写:

DELETE
FROM DevProj
WHERE
    DeveloperID = 1 AND
    ProjectID = 2 AND
    WorkDate) = '2018-01-01';

或者你可以使用更长的版本:

           SELECT * FROM table 

答案 1 :(得分:1)

或者,删除几条记录:

DELETE FROM DevProj 
WHERE (DeveloperID, ProjectID, WorkDate) IN ((1,2,'2018-1-1'), ((1,2,'2018-1-2'))

其他性能注意事项

但请注意,如果您的MySQL版本低于5.7.11,则不会利用索引优化(请参阅https://dev.mysql.com/doc/refman/5.7/en/range-optimization.html#row-constructor-range-optimization)。在这种情况下,您应该使用AND / OR运算符:

DELETE FROM DevProj 
WHERE (DeveloperID = 1 AND ProjectID = 2 AND WorkDate = '2018-1-1') 
OR (DeveloperID = 1 AND ProjectID = 2 AND WorkDate = '2018-1-2')