In my project I am using one MySQL table to store actual information for every id (unnecessary fields are omitted):
CREATE TABLE mytable (
`id` varchar(8) NOT NULL,
`DateTime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM
I need to update rows in this table and insert new DateTime only if this incoming DateTime is newer. But at the same time I do not know if the row with such id already exists in the table. Here is the pseudo-code of what I would like to achieve:
if id does not exist
insert id and DateTime
else if newDateTime > DateTime
update DateTime
I tried to use replace, but as far as I know it is not possible to compare fields from within replace body.
I tried to use update, but if row does not already exist - new information is not being inserted.
Is it possible to do something like this in one query? And if not - what could be the workaround?
PS: I do not think that I have permission to add stored procedures, so this should be a last resort.
I've tested this and it works. And I'm pretty proud of it.
INSERT INTO mytable (`id`,`DateTime`)
VALUES ('your_new_id','your_new_DateTime')
ON DUPLICATE KEY UPDATE `DateTime` = IF(`DateTime` < 'your_new_DateTime', 'your_new_DateTime', `DateTime`)
Related
I have a case where I need to insert or update multiple entries in a table corresponding to a key.
What I'm currently doing is, delete all entries from the table corresponding the key and inserting them all. In case of a table with delete-marker, an update statement is executed to mark all as deleted and new entries are inserted/updated there after.
The case is as shown below, thanks to link
The difference in my situation is, source is not a different table.
for example, for the table PizzaDay, the schedule dynamically changes. So when a reschedule happens, new entries needs to be inserted/updated, and non-pizza days needs to be deleted/marked-deleted (adding a new delete marker is also okay).
CREATE TABLE PizzaDay (
`Id` int
, `CreatedOn` datetime(3) NOT NULL
, `ModifiedOn` datetime(3) NOT NULL
, `StartDate` datetime(3) NOT NULL
, `EndDate` datetime(3) NOT NULL
, PRIMARY KEY (`Id`, `StartDate`, `EndDate`)
);
Any idea how to achieve this in single statement?
I have an InnoDB table with a timestamp in it, and I wish to have another field which carries only the date part of the timestamp, so that I can create an index on it. (My temporal queries will always be bound by date, so having an index with high cardinality on the timestamp is not really needed.)
Is it possible to have the date field update automatically ON UPDATE from the timestamp field (similar to how CURRENT_TIMESTAMP works)?
I tried the following but it MySQL says I have an error in my SQL syntax.
CREATE TABLE test_table (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`full_ts` timestamp NULL DEFAULT NULL COMMENT 'The full timestamp',
`only_date` date NULL DEFAULT NULL ON UPDATE date(full_ts) COMMENT 'This field carries only the date part of the full timestamp for better indexing.',
PRIMARY KEY (`id`),
KEY `ONLY_DATE_IDX` (`only_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I could of course update both fields everywhere in the code, but it would be cleaner if the only_date field was a slave of the full_ts field, updated and kept consistent by the database.
I know that in MySQL 5.7.5 there was a new feature added for stored generated columns, which seem to do exactly this. Unfortunately it is not possible to upgrade the database version at the moment.
Is there a way to achieve this in MySQL 5.5?
This will update the "only_date" column when you update the "full_ts" column
CREATE TRIGGER `autoDate` BEFORE UPDATE ON `test_table` FOR EACH ROW BEGIN
SET NEW.only_date=DATE(NEW.full_ts);
END
EDIT:
For further reading on triggers, please refer to https://dev.mysql.com/doc/refman/5.5/en/create-trigger.html
Also worth reading about triggers https://dev.mysql.com/doc/refman/5.5/en/faqs-triggers.html
I got some data defined in a table in a MySQL database like this
CREATE TABLE `T_dev` (
id VARCHAR(20) NOT NULL,
date DATETIME NOT NULL,
amount VARCHAR(9) DEFAULT NULL,
PRIMARY KEY (id,date)
);
I then insert a record, for example
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','35')
However, one month later I get a report that tells me that this exact record should have amount equal to 30, thus
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','30')
However, that can´t be done because of the primary key I´ve defined. I would like to overwrite the old record with the new one, but not really change my primary key. Any suggestions?
Thanks.
Alexander
Since the record already exists, you don't use the INSERT statement. Instead use an UPDATE statement to change the value to 30 for that specific id and date combination:
UPDATE T_dev SET amount = '30'
WHERE id = '10000' AND date = '2009-08-05 23:00:00'
Just an observation, your table is a little out of the norm. Typically primary keys are of type INT and your amount would probably be better off as a DECIMAL.
use an update statement
UPDATE T_dev
SET amount = 30
WHERE id=10000 AND date = '2009-08-05 23:00:00'
I have a table called promotion_codes
CREATE TABLE promotion_codes (
id int(10) UNSIGNED NOT NULL auto_increment,
created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
code varchar(255) NOT NULL,
order_id int(10) UNSIGNED NULL DEFAULT NULL,
allocated_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This table is pre-populated with available codes that will be assigned to orders that meet a specific criteria.
What I need to ensure is that after the ORDER is created, that I obtain an available promotion code and update its record to reflect that it has been allocated.
I am not 100% sure how to not grab the same record twice if simultaneous requests come in.
I have tried locking the row during a select and locking the row during a update - both still seem to allow a second (simultaneous) attempt to grab the same record - which is what I want to avoid
UPDATE promotion_code
SET allocated_at = "' . $db_now . '", order_id = ' . $donation->id . '
WHERE order_id IS NULL LIMIT 1
You can add a second table which holds all used codes. So you can use an unique constraint in the assignment table to make sure that one code is not assigned twice.
CREATE TABLE `used_codes` (`usage` INTEGER PRIMARY KEY auto_increment,
`id` INTEGER NOT NULL UNIQ, -- This makes sure, that there are no two assignments of one code
allocated_at datetime NOT NULL);
You add the ID of an used code into the used_codes table, and query which code you used afterwards. When this two operations are in one transaction, the entire transaction will fail when there is a second try to use the same code.
I did not test the following code, you might to adjust it.
Also you need to make sure that you have your server meets the requirements for transactions.
-- There are changes which have to be atomic, so don't use autocommit
SET autocommit = 0;
BEGIN TRANSACTION
INSERT INTO `used_codes` (`id`, `allocated_at`) VALUES
(SELECT `id` FROM `promotion_codes`
WHERE NOT `id` in (SELECT `id` FROM `used_codes`)
LIMIT 1), now());
SELECT `code` FROM `promotion_codes` WHERE `id` =
-- You might need to adjust the extraction of insertion ID, since
-- I don't know if parallel running transactions can see the maximum
-- their maximum IDs. But there should be a way to extract the last assigned
-- ID within this transaction.
(SELECT `id` FROM `used_codes` HAVING `usage` = max(`usage`));
COMMIT
You can use the returned code if the transaction sucseeded. If there where more than one processes running to use the same code, only one of them succed, while the rest fails with insert errors about the duplicated row. In your software you need to distinguish between the duplicated row error and other errors, and reexecute the statement on duplication errors.
How to have only 3 rows in the table and only update them?
I have the settings table and at first run there is nothing so I want to insert 3 records like so:
id | label | Value | desc
--------------------------
1 start 10 0
2 middle 24 0
3 end 76 0
After this from PHP script I need to update this settings from one query.
I have researched REPLACE INTO but I end up with duplicate rows in DB.
Here is my current query:
$query_insert=" REPLACE INTO setari (`eticheta`, `valoare`, `disabled`)
VALUES ('mentenanta', '".$mentenanta."', '0'),
('nr_incercari_login', '".$nr_incercari_login."', '0'),
('timp_restrictie_login', '".$timp_restrictie_login."', '0')
";
Any ideas?
Here is the create table statement. Just so you can see in case I'm missing something.
CREATE TABLE `setari` (
`id` int(10) unsigned NOT NULL auto_increment,
`eticheta` varchar(200) NOT NULL,
`valoare` varchar(250) NOT NULL,
`disabled` tinyint(1) unsigned NOT NULL default '0',
`data` datetime default NULL,
`cod` varchar(50) default NULL,
PRIMARY KEY (`eticheta`,`id`,`valoare`),
UNIQUE KEY `id` (`eticheta`,`id`,`valoare`)
) ENGINE=MyISAM
As explained in the manual, need to create a UNIQUE index on (label,value) or (label,value,desc) for REPLACE INTO determine uniqueness.
What you want is to use 'ON DUPLICATE KEY UPDATE' syntax. Read through it for the full details but, essentially you need to have a unique or primary key for one of your fields, then start a normal insert query and add that code (along with what you want to actually update) to the end. The db engine will then try to add the information and when it comes across a duplicate key already inserted, it already knows to just update all the fields you tell it to with the new information.
I simply skip the headache and use a temporary table. Quick and clean.
SQL Server allows you to select into a non-existing temp table by creating it for you. However mysql requires you to first create the temp db and then insert into it.
1.
Create empty temp table.
CREATE TEMPORARY TABLE IF NOT EXISTS insertsetari
SELECT eticheta, valoare, disabled
FROM setari
WHERE 1=0
2.
Insert data into temp table.
INSERT INTO insertsetari
VALUES
('mentenanta', '".$mentenanta."', '0'),
('nr_incercari_login', '".$nr_incercari_login."', '0'),
('timp_restrictie_login', '".$timp_restrictie_login."', '0')
3.
Remove rows in temp table that are already found in target table.
DELETE a FROM insertsetari AS a INNER JOIN setari AS b
WHERE a.eticheta = b.eticheta
AND a.valoare = b.valoare
AND a.disabled = b.disabled
4.
Insert temp table residual rows into target table.
INSERT INTO setari
SELECT * FROM insertsetari
5.
Cleanup temp table.
DELETE insertsetari
Comments:
You should avoid replacing when the
new data and the old data is the
same. Replacing should only be for
situations where there is high
probability for detecting key values
that are the same but the non-key
values are different.
Placing data into a temp table allows
data to be massaged, transformed and modified
easily before inserting into target
table.
Deleting rows from temp table is
faster.
If anything goes wrong, temp table
gives you an additional debugging
stage to find out what went wrong.
Should consider doing it all in a single transaction.