What?
My task was to add some data to the tables that I did not designed, and there I can’t add some KEYS for me to determine if some rows has the same values in some fields. I’ve been digging through documentation and this is what I’ve came up with;
How?
In MySQL we can add some data using INSERT + SELECT:
INSERT INTO sexy_table (cell1, cell2, cell3) SELECT 'valueForCell1', 'valueForCell2', 'valueForCell3'
If there is no fields in select (known as “rows have gone for a beer”) INSERT will not continue to execute and no error will be thrown.
Now, to have empty SELECT (known as don’t insert anything!) we have to add some logical conditions that will give us FALSE value. But
SELECT 'var1' WHERE 1=2
does not work!
But here a little, tiny, sweet keyword gives us a helping hand: the DUAL keyword.
It will act as dummy table, just to have some compilance withl SQL language. So the statement looks like this:
SELECT 'var1' FROM DUAL WHERE FALSE
Result: no rows, note that 1=2 is equal to FALSE keyword.
Now, non working, but proper, SQL INSERT (who the hell need it?!)
INSERT INTO sexy_table (cell1, cell2, cell3) SELECT 'valueForCell1', 'valueForCell2', 'valueForCell3' FROM DUAL WHERE FALSE
using all of this easy stuff above we can solve our problem: how to chceck if data already exists in DB before inserting.
The Solution
Assuming that cell1 is the cell that has to be unique:
INSERT INTO sexy_table (cell1, cell2, cell3)
SELECT 'valueForCell1', 'valueForCell2', 'valueForCell3' FROM DUAL
WHERE NOT EXISTS( SELECT * FROM sexy_table WHERE cell1 = 'valueForCell1')
Easy huh?
Goodbye word
The example above shows that many of operations we can do before inserting, just use your invention to boost up your queries!
Wystarczy użyć polecenia REPLACE INTO tabela(p1,p2,p3) VALUES(‘1′,’2′,’3′) i spokojnie podnienią się odpowiednie wiersze
odpowiedź autora:
Widać nie zrozumiałeś o co chodzi, tutaj jest mowa o insertowaniu nowego wiersza do tabelki, a nie podmiany istniejących wierszy
Przez: Michał w czerwiec 16, 2009
o 13:35