I have two fields:
last_modified : datetime
updated_at : timestamp
updated_at is a new field which has just been added to the table, last_modified contains accurate dates.
I want to be able to loop through all of the rows in the table, selecting the last_modifed datetime, converting it into a timestamp and saving it in the new updated_at field.
Have no idea how to do this, any help is much appreciated!
Try
update table_name set updated_at=unix_timestamp(last_modified);
I don't why you want to store same data twice. Storing same data twice may result into inconsistency.
If you want timestamp in your code, you can do that in code itself.
If your table is called some_table, then you can put this in your migration's up class method:
execute 'UPDATE some_table SET updated_at = last_modifed'
MySQL should be able to convert from datetime to timestamp automatically. In an SQL SET clause, the columns are specific to a single row and the SET applies to all matched rows; without a WHERE clause the UPDATE applies to all rows in the table. Remember that SQL is set-based so everything operates on sets of rows and loops don't really fit the model.
I'm assuming that you're using ActiveRecord as you have a timestamp called updated_at. If you're not using ActiveRecord then you'll have to find another way to send the SQL UPDATE to the database.
Related
I am having`a whole mysql table of approx 40,000 rows with a column named 'epoch_time' and there is epoch time in it and I want to convert that whole table's 'epoch_time' to a equivalent 'date' together in a single sql query and I'm doing this is in php_my_admin . Thanks in advance.
I guess by epochtime you mean UNIX-style timestamps, that is, number of seconds since 1970-01-01T00:00Z. If my guess is wrong, so is the rest of my answer.
First you add a new column to the table.
ALTER TABLE mytable ADD COLUMN datestamp DATETIME AFTER epochtime;
This names the new column datestamp and puts it right after epochtime in the list of columns.
Then you update the whole table to populate the new column from the old using FROM_UNIXTIME(). Omitting the WHERE clause makes the update work on the whole table (careful!).
UPDATE mytable SET datestamp = FROM_UNIXTIME(epochtime);
Finally, if you wish you can drop the old column.
UPDATE TABLE mytable DROP COLUMN epochtime;
If I were you I'd try all this on a copy of your database to ensure it is correct before doing it on your production database.
If your epochtime values already have the TIMESTAMP data type, they are already stored internally as UTC (f/k/a GMT) times. The update operation I suggested will convert them to local time according to the settings on your server.
If your application has users in multiple time zones, you may wish to keep using the TIMESTAMP datatype: it honors time zone settings. If your epoch times are stored in an INT column, you can create your new column with the TIMESTAMP rather than DATETIME type by substituting this line for the first one in my instructions above.
ALTER TABLE mytable ADD COLUMN datestamp TIMESTAMP AFTER epochtime;
I'd like to record the last user and last time a particular row was either inserted or updated in a MySQL table. What is the best way to go about this? Is there some MySQL metadata I can investigate or do I need to create username and timestamp columns myself and then create triggers to populate them?
You need to create separate columns yourself for timestamp and user name. For timestamps there is no need to use triggers to update its value, just declare the timestamp field to use current timestamp as initial value and update value:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
The user is bit more interesting. If you are talking about mysql level user, then yes, use triggers or stored procedure using the USER() function. If you are talking about application level users, then I would supply that username as part of the update statement.
UPDATE table SET username='xxx', ... WHERE ...
You can use a column and set it default system date for insert
For update you must use trigger or etcs.
At least in MySQL 5.5.46, you can track tables. This includes structure and data. There, the DB username and timestamp is recorded.
MySQL has a data type called timestamp. This is a date time field that is updated to now() when any data in the record is changed.
How can I achieve the same behaviour in SQL Server?
I know about the rowversion data type in SQL Server. I don't want this - I want an auto-updating date time value.
Create an INSTEAD OF INSERT trigger, in which you insert into your table, selecting all the columns from INSERTED except for the date time column you want to always reflect the current date time, and insert GETDATE() in for that column.
Then create an INSTEAD OF UPDATE trigger, and do something similar, running an UPDATE statement against the table from inserted, using GETDATE() for that specific column.
To emulate MySQL's TIMESTAMP column you'll need a DATETIME2(7) column and an INSTEAD OF UPDATE trigger. And use the SYSDATETIME function to populate the datetime2 column.
I am trying to convert my column into a DATE format.
It is currently in varchar and displays as: 12/06/2013
I run the following query;
UPDATE dispatch
SET dispatchdate = DATE_FORMAT(STR_TO_DATE(dispatchdate, '%d/%m/%Y'), '%d-%m-%Y');
ALTER TABLE dispatch
CHANGE dispatchdate dispatchdate date;
However after running this query, it displays my data as: 0000-00-00
I am trying to change it so that it will display as DD-MM-YYYY not YYYY-MM-DD
0000-00-00 is mysql's special way of displaying a "zero" or "dummy" date.
Like many of mysql's oddities, you learn to live with it and I suggest you:
UPDATE dispatch SET
dispatchdate = null
WHERE dispatchdate = '0000-00-00'
Or set to whatever value works best for you.
You'll have to build a scratch column: you cannot change the data type of a column in place, and expect to keep the data. It just won't work.
So
Add a new datetime column, maybe named tmp_dispatchdate
Use the query you've written to write the datetime value into that column
After confirming that the data converted correctly, drop dispatchdate
Rename tmp_dispatchdate to dispatchdate
If you have a primary key on the table in question, you can do all the "middle" work in a temp table, if you prefer, using the PK to reference the right record. But you'll still have to drop a column and add a column to do what you're trying to do.
After inserting new data into a table, I need to select some of the new data straight after, so I can use it for inserting into another table.
The only way I can think of doing this is using the 'datetime' field I have in my row, but how would I retrieve the latest date/time inserted.
INSERT statement with NOW() value for datetime
society_select = SELECT socID, creator, datetime FROM societies.society WHERE datetime='[..datetime is the newest...]';
Hope that makes sense. Thank you
There are a number of ways to do this.
Why not make use of a trigger for this?
When a trigger creates a record you can get the id's of the records inserted. You can then do a select and insert new values into the relevant table.
MYSQL has loads of resources on using triggers.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Or you can get the number of rows affected then use this to get the required result set in a select statement.
Get the last inserted ID?
If you are inserting one row into the database at a time then you would be able to get the last inserted id from MYSQL. This will be the Primary Key value of the record you last inserted into the database.
You would basically do something like this in mysql:
SET #inserted_id = LAST_INSERT_ID();
Or in PHP you can use the function:
mysql_insert_id(&mysql);
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Sort the results by their datetime in descending order, and select the first of them.
society_select = SELECT socID, creator, datetime FROM societies.society ORDER BY datetime DESC LIMIT 1;
you can use this with an auto increment filed. after inserting data you can retrieve the list inserted id from the table. and use that id to get the latest record.
A trigger as suggested is an option. If you don't want to use that for some kind of reason you can:
Add an integer primary key with auto_increment as ID and sort it DESC (e.g. INT(11))
Sort descending on a timestamp column (ofcourse with an index on it)
Use a trigger after inserting the data. This is for sure the cleaner way.
Another option is to use a method like mysql_insert_id. Assumed that you use PHP. There are of course equivalent methods in other languages as well.
Sorting is not an option(if not wrapped smart in transaction) - If you have multiple writes and reads on the table this might end up pretty ugly.