0

I need to add IF EXISTS Then UPDATE Else INSERT to the following queries:

-- Exist
UPDATE TargetTable
SET ColumnD = '...', ColumnE = '...'
WHERE ...

-- Doesn't Exist
INSERT INTO TargetTable
SELECT ColumnA, ColumnB, ColumnC, ColumnD, ColumnE, ColumnF, ColumnG
FROM (SELECT DISTINCT ColumnB, ColumnC from SourceTable) derived_table
WHERE ColumnB = 'a';

NOTE: Both Source and Target tables have no PK due to the nature of data in it.

EDIT: the "duplicate" question/answer doesn't work for me because my tables has no primary keys.

  • The question @Shift'NTab referenced should work as long as you have at least one unique key; but since you have no PK, I doubt you'd have a unique one. In that case, you'll need procedural code; you can either do that in your client language or a stored procedure; MySQL does not support it's procedural elements in normal queries. – Uueerdo May 31 '18 at 17:54
  • Make sense. I have already tried the suggested solution but, like you said, doesn't work in my case since there is no PK – Carlo Santana May 31 '18 at 17:56
  • Care to explain why there is no pk or combination of unique columns? – Shift 'n Tab May 31 '18 at 19:29
  • because an item "Box" can be move in and out of a room multiple times per day. The table records the box's in-out times along with many other objects. – Carlo Santana May 31 '18 at 19:43
  • Sidenote: Your insert...select makes no sense unless `Column[A|D|E|F|G]` are local variables whose declarations have been omitted. – Uueerdo May 31 '18 at 20:36

0 Answers0