Working on some postgreSQL queries. As I said in a previous question..my knowledge of SQL logic is quite limited..
I have this query that inserts a row.
$timestamp = date('Y-m-d G:i:s.u');
$check_time = "start"; //can also be stop
$check_type = "start_user"; //can also be stop_user
$insert_query = "INSERT INTO production_order_process_log (
production_order_id,
production_order_process_id,
$check_time,
$check_type)
VALUES (
'$production_order_id',
'$production_order_process_id',
'$timestamp',
'$user')
";
Unfortunately, that is adding a new row every time. I would like to add conditional SQL so that
if the production_order_process_id doesn’t exist, do the INSERT as it’s written in the query above. That is, add the new row with all the new information
but if the production_order_process_id does exist and the check_type is stop_user then UPDATE the row to fill the column stop with the $timestamp and fill the column stop_user with $user.
I understand this is complicated.. Or, at least for me it is ^^ Thanks much for the help!
This is usually called
MERGEor upsert. PostgreSQL doesn’t have explicit support for this operation.The best article I’ve seen on the topic of
MERGEin PostgreSQL is this one by depesz .