Order by in a update query - mysql

UPDATE table1
SET date1 = DATE_FORMAT(DATE_ADD(STR_TO_DATE(date1,'%m/%d/%Y'),INTERVAL 1 DAY),'%m/%d/%Y'),
date2 = date2 + 1*24*60*60
ORDER BY STR_TO_DATE(date1,'%m/%d/%Y') DESC;
I am trying to update all dates in table1 1 day a head (using MySql), I am using the query above.
in table1, ad_id + date1 represent a uniqe key and thats why I am using the Order By line.
this query worked on my local data base but when I run it on anther data base I get this error:
Duplicate entry '40001305194-07/02/2018' for key 'ad_id_2'
this doesn't make sense since in the data base their is no date 07/02/2018 for this ad_id.
and for date 07/01/2018 there is only 1 line for this ad_id.
what am I doing wrong, thanks in advance :)

Related

MAX() + ADD_DATE - per update su Mysql

I'm trying to perform a field update on mysql with a MAX() value getting other columns of the same table .
For instance, I've this table:
id starting_date activity_1 activity_2 activity_3
1 0000-00-00 10 5 12
I'm trying this query (it doesn't work):
$today="2022-07-20"; //It's a dynamic var generate via date()
UPDATE table_name SET starting_date = DATE_ADD('2022-07-20',(INTERVAL (SELECT GREATEST(activity_1,activity_2,activity_3) FROM table_name WHERE id ='1') MONTH) WHERE id ='1'
My desire is to add 12 months (or the greatest value) to 2022-07-20...
I'm trying several queries with no positive result
Any idea around?
Thanks
Use multiple-table UPDATE syntax.
UPDATE table_name
JOIN ( SELECT id,
GREATEST(activity_1,activity_2,activity_3) interval_for_update
FROM table_name ) value_for_update USING (id)
SET starting_date = '2022-07-20' + INTERVAL interval_for_update MONTH
-- WHERE id = 1
PS. Never enclose numeric literal values with the quote chars - this converts them to strings and causes excess implicit data convertions.

how to update a sql database table based on the condition from another table in the same database

I have a two tables in a database.
table_1(device_ID, date,voltage)
table_2(device_ID,device_status)
I am trying to create an event to execute every 5 minutes.
What I am trying to achieve is, select device_ID from table_1 if there is no new data over the last 10 minutes and update the table_2, that means set device_status to 0.
How do i pass conditions between two tables?
BEGIN
select device_ID from table_1 where date = DATE_SUB(NOW(), INTERVAL 10 Minutes);
//here i will get device_IDs if there was a data within last 10 minutes.
//but i need device_ID if there were no data.
//how to update table_2 based on the above condition?
END
You can use the results of your first query as a subquery to de-select rows (by using NOT IN) for the UPDATE:
UPDATE table2
SET device_status = 0
WHERE device_ID NOT IN (select device_ID
from table_1
where date > DATE_SUB(NOW(), INTERVAL 10 Minutes))
Note I think you probably want >, not = in your where condition in the subquery.

MySQL - update the row's date and save the time

I want to update a row which has timestamp datatype named date_start. Here's an example:
date_start = 2017-04-26 12:34:11
I want to update it, but to save the time, so it'll look like this:
date_start = 2017-05-28 12:34:11
Any ideas? So far I tried extract method and concat method.
Best Regards..
If you just want to update the date component of the timestamp while retaining the time component then you can build the updated timestamp using string concatenation with TIME():
UPDATE yourTable
SET date_start = CONCAT('2017-05-28 ', TIME(date_start))
WHERE <some condition>
Demo

Replace values in MySQL colums from row x to row y

I'd need to replace post dates from wordpress post table.
There are >800.000 post entries with the same date because of a migration.
How can I replace the date by "from row x to row"?
For example:
row 1 - 10.000 should have date 2013-01-02 09:20:10
row 10.001 - 20.000 should have date 2013-02-05 12:30:21
and so on...
Or maybe replacing by post id?
I know there is a sql query to do this, but I can not remember which one and how to use it correctly.
try adding a LIMIT to the sql to update rows:
UPDATE {table}
SET {datefield} = "{desired date}"
WHERE {datefield} = "{bad date}"
LIMIT 10000;
this will update 10000 rows at a time with a new date as desired, however it's not particularly picky about which ones get updated in which order, generally it will be in the database's internal order which is (roughly) chronological.
is there any other part of the data you can use to determine which records should be updated with which date?
This is not what you asked for, but might be better. You can create distinct timestamps, as if a post has been created every X seconds:
update posts
set created = timestamp('2013-01-02 12:00:00') + interval id * 140 second
where 1=1
http://sqlfiddle.com/#!9/a6c7e0/2
You can even make them look random:
update posts
set created =
timestamp('2013-01-02 12:00:00')
+ interval id * 140 second
+ interval floor(rand()*140) second
where 1=1
http://sqlfiddle.com/#!9/b394c/1

Sql Query to find out Last Five Reords which created Or updated and before how much time with created and modified Date?

I have one table name as a_campaign in MySQL Database that have following columns
CampaignId | name | Created Date | Modified Date |
Now What I want is to Display Latest 5 Records From the Above table as Recently Created Or Recently updated ...
I don't know How can I fetch this records as per my requirement..so please if anyone can guide me..
My Resulted Data Should be Fetched Like Following
Campaign Id | Campaign Name | Status(Updated/Created) | Time (Created/Modified Before)
the last column should be shows the times that campaign Created or updated before how many Months/Weeks/days/hours/minutes/seconds comparing with today's date)
Please Help Me Out..
This should achieve it. You can adjust the last column to be formatted as you wish, but that gives how many minutes ago the activity occurred
SELECT
campaignId,
name,
CASE WHEN modifieddate > createddate THEN 'Updated' ELSE 'Created' END AS type_of_activity,
modifieddate AS latest_activity,
TIMESTAMPDIFF(MINUTE,modifieddate,NOW()) AS minutes_ago
FROM
a_campaign
ORDER BY
modifieddate DESC
So I'm not quite understanding your desired resultset structure, but to sort by either column, you could do this:
select *, greatest(Created, Modified) as lastDate
from a_campaign
order by lastDate desc
limit 5;
Note that this does a full table scan. So you might want to add constraints on both Created and Modified (say either one need to be more recent than 24 hours ago) to limit the size of your resultset (indexes on the date columns would help)
Additionally, to make this simple, I assume Modified is always greater or equal than Created. So you should make your app populate both Created and Modified at row creation time, and update only Modified on change. If you do that, you can simplify the query to only sort by the Modified column DESC, and get the top 5.
[Edit] I just saw you added a sample of your dataset, which indicates that both Created and Modified are populated at row creation time. In that case, it sounds like you just need a sort on the Modified column:
select *
from a_campaign
order by Modified desc
limit 5;
please use this procedure
DECLARE #TABLES TABLE(ID INT , Name NVarchar(50),status NVarchar(50), time int,time1 datetime)
INSERT INTO #TABLES
SELECT ID,Name,'Created',DATEDIFF(D,CreatedDate,GETDATE()),CreatedDate FROM Compaign WHERE CreatedDate > ModifiedDate
INSERT INTO #TABLES
SELECT ID,Name,'Updated',DATEDIFF(D,ModifiedDate,GETDATE()),ModifiedDate FROM Compaign WHERE CreatedDate <= ModifiedDate
select ID 'Campaign Id' ,Name 'Campaign Name', status 'Status(Updated/Created)', time 'Time (Created/Modified Before)' from #TABLES order by time1 asc