Mizbah Ahsan
Mizbah Ahsan

Reputation: 1262

mysql: update a query if not exist any row by where condition then insert a new data

I need to update a table by some condition, not with primary key.

I am trying to do something like following

update p_price set price = :price where p_id = :pid and c_id = :cid if there is no any row with where p_id = :pid and c_id = :cid then insert into p_price (p_id, c_id, price) value (1,2,3)

is that possible with sql command?

note: there are no primary key so I can not use ON DUPLICATE KEY.

Upvotes: 1

Views: 291

Answers (1)

John Woo
John Woo

Reputation: 263853

Actually it doesn't need to have a primary key. It only needs atleast unique constraint. Add this UNIQUE constraint

ALTER TABLE p_price ADD CONSTRAINT tb_unique UNIQUE(p_id , c_id);

and execute this statement,

insert into p_price (p_id, c_id, price) 
value (1,2,3)
ON DUPLICATE KEY 
UPDATE price = :price

just change the values that first your needs.

Upvotes: 4

Related Questions