Sanjai Kummar
Sanjai Kummar

Reputation: 91

if same columns values are repeated in multiple rows then UPDATE - SQL / MYSQL

I have a table like this

create table if not exists cms(
  id int(11) not null auto_increment primary key,
  cms_id varchar(20),
  published_datetime varchar(30),
  last_modified_datetime varchar(30),
  score float,
  access_vector varchar(45),
  access_complexity varchar(45),
  authentication varchar(45),
);


INSERT INTO `cms` (`id`, `cms_id`, `published_datetime`, `last_modified_datetime`, `score`, `access_vector`, `access_complexity`, `authentication`) VALUES
(1, 'CMS-2002-0493', '2002-08-12T00:00:00.000-04:00', '2016-10-24T11:23:01.940-04:00', 7.5, 'NETWORK', 'LOW', 'NONE')

enter image description here

in simple words if same value of cms_id gets repeated then update the whole row (update all columns based on cms_id)

now I need an output like only the last inserted cms_id value should be present in table other all same cms_id should be deleted and updated with last entry

coulmn id with primary key 1,613,1225 should be deleted and only 1837 should be present

I need output something like below image

enter image description here

totally it should replace the repeated cms_id column as per last entry.

accordingly if cms_id value repeats then it should delete the existing cms_id value and it should update all the other column values as per last insert entry , need query for this

Upvotes: 2

Views: 567

Answers (1)

Isaiah
Isaiah

Reputation: 680

MySQL has a special REPLACE command that works exactly like INSERT except it replaces the row if the primary key or an unique has the same value.

REPLACE INTO cms ...

Where ... represents the rest of the query.

Disclaimer: This SQL statement is a special extension made by MySQL; it is not part of the SQL standard and probably won't work on other DBMS.

Upvotes: 2

Related Questions