Getting all records that are 3months old in Postgres - php

I need to find all records that are exactly 3months old in Postgres
My query looks as follows.
SELECT * FROM adds WHERE adtype = 'CL' AND DATEDIFF(dstart,DATE(now())) = DATE_SUB(curdate(),interval 3 month);
But this does not seem to work. Any advise help with this query will be helpful. I can calculate this in PHP but want to find out the value using a Postgres query.

You are comparing a time period to a point in time.
Is there really a DATEDIFF in Postgres?
Are you sure you need the records of that one day exactly 3 months in the past? Unusual application.
I'd suggest: WHERE DATE(dstart) = DATE(NOW())-INTERVAL '3 month'

Related

Proper MYSQL syntax for timestamp comparison and distinct results with certain exclusions

Sorry for asking, but I've never had to do such a complex MYSQL query before and I don't actually know what to google search in order to get the answer.
I have a poorly crafted database with a table of appointments of pregnant women that includes the day they came and the number of weeks pregnant they were at that time. I'm trying to select each one that should be 30 weeks right now but that doesn't already have a separate entry after 25 weeks pregnancy. I use the phone number to uniquely identify each person.
Since I really don't know how to formulate this query, this is the best I've come up with.
SELECT * FROM patientlist WHERE
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`) - `weekspreg`*604800) > 29*604800
AND
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`)- `weekspreg`*604800) <= 30*604800
AND
/* a subquery that keeps out results where the phone number would show up elsewhere in the table for a woman with more than 25 weeks of pregnancy. */
There has to be a better solution than separately querying each of the results from the date range by phone number to see if the weekspreg is more than 25.
Thank you in advance for any help or direction.
Your entire WHERE is incorrect. A query can only have ONE where clause. You join multiple conditions with and and or, not and where:
WHERE foo AND bar // correct
WHERE foo AND WHERE bar // syntax error
Check out the MySQL Date and Time Functions. For example, I'm not entirely certain what that last WHERE clause is trying to do, but I believe the first portion could be rewritten as something like:
SELECT *
FROM patientlist
WHERE `date` - interval `weekspreg` week
between now() - interval 29 week
and now() - interval 30 week

MYSQL Group By date + 3 hours

I have a query that counts the "Xp" difference per day from my database, this all works as it should however it groups from midnight-midnight, what I would like to do is group 3am to 3am.
However another issue I think I may have is that my query may not always have the rows being the exact second at 3am due to the fact that it has to run a huge query and retrieve data from another website per user profile, so it should get all data after 3am, but before maybe 4am or something, so it has enough time to get all of the rows.
my current mysql is:
SELECT FROM_UNIXTIME(date, '%Y%m%d') AS YYYYMMDD, MAX(xp)-MIN(xp) AS xp_gain
FROM skills
WHERE userID = '$checkID'
AND skill = '$skill'
AND date >= '$date'
GROUP BY YYYYMMDD
ORDER BY date ASC
The best way to handle this is to add (if you can) another column that is just a DATE (not a DATETIME) and have this field rollover from one day to the next at 3am, (you can to this by subtracting 3 hours from the current time when doing the INSERT).
This gives you a couple of benefits, especially with a large number of rows:
It is much faster to query or group by a DATE than a range of
DATETIME
It will always query the rows at the exact second of 3am,
regardless of how long the query takes.

Symfony and Doctrine Querying For Hour Ranges

In a previous question (SQL query between two times on every day) I asked about querying across a set of data and returning all entries that had dates associated with them that were between two hour values. I'm also trying to exclude Saturday and Sunday. The answer I received is valid when dealing with plain SQL:
SELECT *
FROM yourtable
WHERE TIME(created_at) BETWEEN '08:00:00' AND '15:00:00'
But I actually need to do this while using Symfony2/Doctrine. Not surprisingly when I create the following:
$myQuery= $this->em->createQuery("SELECT f FROM myBundle:Foo f
WHERE f.bar = 1
AND TIME(f.myTimestamp) BETWEEN :myStart AND :myEnd
AND DAYOFWEEK(f.myTimestamp) NOT IN (1,7)")
->setParameter('myStart', $myStart)
->setParameter('myEnd', $myEnd)
->getResult();
I'm getting exceptions because TIME and DAYOFWEEK are not native functions of Doctrine. Is there anything within Doctrine that I can use to perform a similar query or am I out of luck? Thanks.
Neither DAYOFWEEK nor TIME, DAY, ... are supported in DQL.
The quickest way to satisfaction will be a native MySQL query.

How to update/Insert random dates in SQL within a specified Date Range

Please forgive me. I am an absolute newbie and I need help with this table in phpmyadmin
My Table has the following columns:
Primary_ID, Begin_Date, End_Date, Timestamp
How do I update in phpmyadmin, selected rows with randomly generated begin_dates and timestamp within a specified date range (eg: 30 days in a month).
E.g of desired outcome
Primary_id--- Begin_Date -------------Timestamp
1.------------2008-09-02--------------2008-09-02 21:48:09
2.------------2008-09-03--------------2008-09-03 15:19:01
3.------------2008-09-14--------------2008-09-14 01:23:12
4.------------2008-09-27--------------2008-09-27 19:03:59
Date Range between 2008-09-01 and 2008-09-31.
Time is variable 24 hrs
I am a newbie, so a syntax that will work in phpmyadmin will help greatly.
We are making a presentation for a gym site with 500 members but the added member values all have the same begin date and time. Trying to separate them into different monthly registrations in the database, eg 50 people registered in August at different days and times, 35 people in October, etc. Hope it is clearer now. Thanks –
When I try one of the below answers, I get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$randomDate = rand(1,31)' at line 1. So ideally, a code I can copy and paste into phpmyadmin with minimal editing will be appreciated. In sequence if possible. For a total dummy to understand and execute.
I'd start with something like this. A bunch of these can be combined, but I split it up so you can see what I'm doing.
To get random numbers, you can use rand(). Get one for the date, hour, minute, and second
$randomDate = rand(1,31);
$randomHour = rand(1,24);
$randomMinute = rand(0,59);
$randomSecond = rand(0,59);
You will want leading zeros (03 instead of 3) so you can use str_pad to add them, if required
$randomDate = str_pad($randomDate, 2, '0',STR_PAD_LEFT);
//The '2' is how many characters you want total
//The '0' is what will be added to the left if the value is short a character
Do the same with all your other random values.
Just because I like neat queries, you should make up your final update strings next.
$newDate = '2008-09-'.$randomDate;
$newTime = $randomHour.':'.$randomMinute.':'.$randomSecond;
Now I don't know how you're determining which rows you want to update, so I will leave that up to you. For an example, I will show you a query if you wanted to do this with Primary_id 3:
$x = mysql_query("UPDATE yourTable SET Begin_Date=\"$newDate\", Timestamp=\"$newTime\" WHERE Primary_id = 3");
something like:
insert into myTable (begin_date) values date_add('2008-09-01', INTERVAL RAND()*30 DAY)
that should create a new row with a random begin_date
update myTable set Timestamp = date_add(begin_date, INTERVAL RAND()*1440 MINUTE)
then that one should set the timestamp to a random minute of that day.

How to delete rows based on date differences with MySQL?

I need to delete rows where a datetime field is over 2 weeks old.
This is what I have came up with
$duration = Date::WEEK * 2; // int(1209600)
$query = 'DELETE FROM properties
WHERE TIMEDIFF(' . date(DATE_ISO8601) . ', reserved_datetime) > ' . $duration;
I don't often write complicated queries (preferring to do stuff in PHP, where I'm more comfortable) but I'd like to know more about them, plus doing this sort of thing in PHP would be very inefficient and I am handling a large amount of rows.
Anyone know what I'm doing wrong? Cheers.
Update
I gave Wallyk's answer a shot, changing it slightly in phpMyAdmin to SELECT just so I could see what was going on.
This is what I used
SELECT *
FROM properties
WHERE date_sub( `reserved_datetime` , INTERVAL 2 week ) >0
LIMIT 0 , 30
The only problem however, is that it has returned rows where the reserved_datetime is 2010-02-28 10:45:59, definitely less than 2 weeks ago (from now).
I thought of checking MySQL's internal date. I have been using date(DATE_ISO8601) in my queries, because MySQL's NOW() wasn't exactly right (it just returned if interested 2010-02-28 20:09:19).
Is there a way to specify the current date in that query? Any other suggestions?
Many thanks
Another Update
Here is a screenshot from phpMyAdmin that may demonstrate anything better than my words can. Oh, and the reason it has returned 3 only is because all the others have blank values, i.e. 0000-00-00 00:00:00
wallyk's answer is not correct. Think about what you're doing - subtracting two weeks from almost any date will still be greater than zero (zero = 1/1/1970). I think you want something more like this:
DELETE FROM properties WHERE DATE_SUB(NOW(), INTERVAL 2 WEEK) > reserved_datetime
Use:
FROM PROPERTIES p
WHERE p.reserved_datetime <= DATE_SUB(NOW(), INTERVAL 2 WEEK)
Mind that because of using NOW(), the two week old date will include the time portion.
I don't have a mysql database so I can't say if it works for sure, but it does in postgresql:
DELETE FROM properties WHERE (NOW() - reserved_datetime < interval '2 weeks')
Try this instead:
$query = 'DELETE FROM properties
WHERE date_sub(reserved_datetime, interval 2 week) > 0';
This assumes that reserved_datetime is the field name in the table.
(Tested with MySQL 5.0.46-standard.)

Categories