Poiché le colonne non sono annullabili, devi passare 0
s invece di null
s per le colonne per le quali non vuoi fornire valori in INSERT
dichiarazioni e utilizzare confronti con 0
invece di null
:
INSERT INTO stock (price, stock1, stock2) VALUES
('99', '10', 0),
('120', 0, '12')
ON DUPLICATE KEY UPDATE
`stock1-C` = `stock1-C` + (VALUES(stock1) <> 0 AND stock1 <> 0),
stock1 = stock1 + VALUES(stock1),
`stock2-C` = `stock2-C` + (VALUES(stock2) <> 0 AND stock2 <> 0),
stock2 = stock2 + VALUES(stock2)
Risultato:
prezzo | stock1 | stock1-C | stock2 | stock2-C |
---|---|---|---|---|
99 | 10 | 0 | 0 | 0 |
120 | 0 | 0 | 12 | 0 |
Poi ancora:
INSERT INTO stock (price, stock1, stock2) VALUES
('99', '10', 0),
('120', 0, '12')
ON DUPLICATE KEY UPDATE
`stock1-C` = `stock1-C` + (VALUES(stock1) <> 0 AND stock1 <> 0),
stock1 = stock1 + VALUES(stock1),
`stock2-C` = `stock2-C` + (VALUES(stock2) <> 0 AND stock2 <> 0),
stock2 = stock2 + VALUES(stock2)
Risultato:
prezzo | stock1 | stock1-C | stock2 | stock2-C |
---|---|---|---|---|
99 | 20 | 1 | 0 | 0 |
120 | 0 | 0 | 24 | 1 |
Quindi:
INSERT INTO stock (price, stock1, stock2) VALUES
('150', '55', 0),
('150', 0, '56')
ON DUPLICATE KEY UPDATE
`stock1-C` = `stock1-C` + (VALUES(stock1) <> 0 AND stock1 <> 0),
stock1 = stock1 + VALUES(stock1),
`stock2-C` = `stock2-C` + (VALUES(stock2) <> 0 AND stock2 <> 0),
stock2 = stock2 + VALUES(stock2)
Risultato:
prezzo | stock1 | stock1-C | stock2 | stock2-C |
---|---|---|---|---|
99 | 20 | 1 | 0 | 0 |
120 | 0 | 0 | 24 | 1 |
150 | 55 | 0 | 56 | 0 |
Quindi:
INSERT INTO stock (price, stock1, stock2) VALUES
('150', '10', 0),
('150', 0, '10')
ON DUPLICATE KEY UPDATE
`stock1-C` = `stock1-C` + (VALUES(stock1) <> 0 AND stock1 <> 0),
stock1 = stock1 + VALUES(stock1),
`stock2-C` = `stock2-C` + (VALUES(stock2) <> 0 AND stock2 <> 0),
stock2 = stock2 + VALUES(stock2)
Risultato:
prezzo | stock1 | stock1-C | stock2 | stock2-C |
---|---|---|---|---|
99 | 20 | 1 | 0 | 0 |
120 | 0 | 0 | 24 | 1 |
150 | 65 | 1 | 66 | 1 |
Vedi la demo
.