How can I get the rows from table articles for the last 7 days?
Each row has a value timestmp where time is set via time().
I've tried this:
SELECT COUNT(*) FROM `articles` WHERE `timestmp`>NOW()-INTERVAL 168 HOUR
It doesn't work for me :(
The table is:
CREATE TABLE `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`link` text NOT NULL,
`article_name` text NOT NULL,
`descript` text NOT NULL,
`preview` text NOT NULL,
`content` text NOT NULL,
`category` int(11) NOT NULL,
`author` text NOT NULL,
`keywrds` text NOT NULL,
`timestmp` int(11) NOT NULL,
`modified` int(11) NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT (`keywrds`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
The expected output is all the articles for the last 7 days with names, descriptions and so on.
Your timestmp column should be storing a UNIX timestamp, which is the number of seconds since the start of the UNIX epoch in January 1, 1970. So, if you just want records which happened exactly within the last 7 days, then you may just subtract 7 days (as seconds) from your timestmp column:
SELECT COUNT(*) AS cnt
FROM articles
WHERE timestmp > UNIX_TIMESTAMP() - 7*24*60*60;
If instead, you want records from 7 days ago, including the entire first day, then we need to do more work. In this case, we have to compute midnight on the first day, then convert that to a UNIX timestamp.
SELECT COUNT(*) AS cnt
FROM articles
WHERE timestmp > UNIX_TIMESTAMP(DATE(NOW() - INTERVAL 7 DAY))
Related
I have two tables in my database. In the first table is a column named date where i insert a date period in a 1 day interval. In the second table are the calendar weeks of the same date period and an autoincrement column weekid.
For example I have the calendar week 25 with the weekid 145 (saved in the second table). The date area is from 21.06-27.06 and is saved in the first table.
Now i want to insert the weekid into the first table for every day (date) matching the calendar weeks.
Here are my tables:
CREATE TABLE `day` (
`dayid` int(255) NOT NULL AUTO_INCREMENT,
`userid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`dayid`)
CREATE TABLE `week` (
`weekid` int(255) NOT NULL AUTO_INCREMENT,
`userid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`calendar week` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`year` year(4) NOT NULL,
PRIMARY KEY (`weekid`
Example output for table "day":
weekid: 145
userid: 589
date: 2021-05-06
Example output for table "week":
weekid: 145
userid: 589
calendar week: 25
year: 2021
Does anyone have an idea how to do the date comparison?
If in the second table you don't have the dates of each week you can just calculate it on the first table right?
SELECT (EXTRACT(DOY FROM date_in_table1)/7)
should produce the work week of a certain date.
I have a mysql query in php that is set to run hourly by a cron job. Sometimes the results are correct and sometimes I get back a result thats on a different date than being queried. As mysql is being run in a different timezone i am using php date() time() to correct the current hour and date. I first use count in mysql to every see if any records exist matching the criteria. And if they do i run the same query and grab the data. I am looking for records that are for the current day. Have a time frame of an hour or hour and a half ahead of the current time and match a couple other parameters being the JobStatus and TechID columns. Sometimes it runs correctly and sometimes I get records showing that are for days ahead. The column for the time in the database is a varchar as I just simply needed the current time to match a string as the appointment is entered into the database as 1PM or 9:30AM or whatever time slot was selected on the form in hour or half hour time frames. I have as well added my database structure below too. I have checked the database to see if its corrupt and it checks out fine.
Am I maybe going about this query incorrectly?
date_default_timezone_set("America/Chicago");
$SearchDate = date('Y-m-d', time());
//CURRENT TIME PLUS ONE HOUR
$TimePlusHour = date('gA', strtotime("+1 hours"));
//CURRENT TIME PLUS ONE HOUR PLUS SETTING MINUTES TO HALF HOUR
$Plus30 = date('g:30A', strtotime("+1 hours"));
$sqlCount = "SELECT COUNT(*) AS 'count' FROM ServiceTickets WHERE Date=
'".$SearchDate."' AND Time='".$Plus30."' OR Time='".$TimePlusHour."'
AND JobStatus='1' OR JobStatus='3' AND TechID= '".$TechID."' ";
$sql1 = "SELECT * FROM ServiceTickets WHERE Date= '".$SearchDate."' AND
Time='".$Plus30."' OR Time='".$TimePlusHour."' AND JobStatus='1' OR
JobStatus='3' AND TechID= '".$TechID."' ORDER BY id ASC";
Database structure
CREATE TABLE `ServiceTickets` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) DEFAULT NULL,
`LastName` varchar(255) DEFAULT NULL,
`Phone` varchar(20) DEFAULT NULL,
`Address` varchar(255) DEFAULT NULL,
`Address2` varchar(255) DEFAULT NULL,
`City` varchar(100) DEFAULT NULL,
`State` varchar(50) DEFAULT NULL,
`Zip` varchar(10) DEFAULT NULL,
`Email` varchar(255) DEFAULT NULL,
`Date` date DEFAULT NULL,
`Time` varchar(50) DEFAULT NULL,
`JobDesc` text,
`JobStatus` varchar(10) DEFAULT NULL,
`TechID` varchar(3) DEFAULT NULL,
`LastModified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
You are confusing your query when calling AND and OR, I would start by putting your OR in parentheses
$sqlCount = "SELECT COUNT(*) AS 'count' FROM ServiceTickets WHERE Date=
'".$SearchDate."' AND (Time='".$Plus30."' OR Time='".$TimePlusHour."')
AND (JobStatus='1' OR JobStatus='3') AND TechID= '".$TechID."' ";
$sql1 = "SELECT * FROM ServiceTickets WHERE Date= '".$SearchDate."' AND
(Time='".$Plus30."' OR Time='".$TimePlusHour."') AND (JobStatus='1' OR
JobStatus='3') AND TechID= '".$TechID."' ORDER BY id ASC";
I'm in need of your help.
What I'm trying to achieve is the following:
Obtain both the withdrawal and deposit profit, for each day, for the past week.
So I'm hoping to get rows with the values: Day, Deposit Profit, Withdrawal Profit.
The catch however is that a day is a custom day, meaning: A day is between yyyy-mm-dd 13:00:00 and yyyy-mm-dd 13:00:00. So a group by date wouldn't be sufficient.
The query I've tried experimenting with was:
SELECT submit_date,
MAX(deposit_amount) - MIN(deposit_amount) AS deposit,
SUM(withdrawal_amount * withdrawal_percentage) as withdrawal
FROM `pro_Profits`
WHERE account_id = '{C795E1D2-452A-DEE8-A800-02E94332114A}'
AND submit_datetime >= NOW() - INTERVAL 1 WEEK
GROUP BY submit_date
ORDER BY `submit_datetime` DESC
Table:
CREATE TABLE IF NOT EXISTS `pro_Profits` (
`id` varchar(512) NOT NULL,
`account_id` varchar(512) NOT NULL,
`submit_date` date NOT NULL,
`submit_time` time NOT NULL,
`submit_datetime` datetime NOT NULL,
`deposit_amount` bigint(20) NOT NULL,
`withdrawal_amount` bigint(20) NOT NULL,
`deposit_percentage` double NOT NULL DEFAULT '1',
`withdrawal_percentage` double NOT NULL DEFAULT '0.4',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `id_2` (`id`),
KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What you basically need to do is shift the day by 13 hours. You can use a function for this in MySQL:
TIMESTAMPDIFF(HOUR,13,submit_date)
In your SQL query this would look something like this:
SELECT
TIMESTAMPDIFF(HOUR,13,submit_date) as shifted_submit_date,
MAX(deposit_amount)-MIN(deposit_amount) AS deposit,
SUM(withdrawal_amount*withdrawal_percentage) as withdrawal
FROM
pro_Profits
WHERE
account_id = '{C795E1D2-452A-DEE8-A800-02E94332114A}' AND
submit_datetime >= NOW()-INTERVAL 1 WEEK
GROUP BY
shifted_submit_date
ORDER BY
submit_datetime DESC
A bit of experimenting might be needed to get exactly what you want. I find it strange that you group by one thing, and order by another.
You can try something like this:
SELECT
FLOOR(TIME_TO_SEC(TIMEDIFF(DATE_ADD(Date(NOW()), INTERVAL 13 Hour),submit_datetime))/86400.00) as Diff,
MAX(deposit_amount)-MIN(deposit_amount) AS deposit,
SUM(withdrawal_amount*withdrawal_percentage) as withdrawal
FROM
pro_Profits
WHERE account_id='{C795E1D2-452A-DEE8-A800-02E94332114A}'
and submit_datetime >= DATE_ADD(Date(NOW()), INTERVAL 13 Hour)-INTERVAL 1 WEEK
GROUP BY
Diff
ORDER BY
Diff
DATE_ADD(Date(NOW()), INTERVAL 13 Hour: You want to start from today at 13:00 and go back 1 week
TIME_TO_SEC(TIMEDIFF(DATE_ADD(Date(NOW()), INTERVAL 13 Hour),submit_datetime))/86400.00: Calculate difference in seconds between our date and 'submit_datetime'
FLOOR(...): we get the upper bound of that difference to create our day "buckets".
Note: count of "buckets" is actually 8, you can also find "-1" if there is a submit on the day you cast your query after 13:00. You can easily edit the above query to remove those results.
I've a big table with about 20 millions of rows and every day it grows up and I've a form which get a query from this table. Unfortunately query returns hundreds of thousands of rows.
Query is based on Time, and I need all records to classify them by 'clid' base on some rules.So I need all records to do some process on them to make a result table.
This is my table :
CREATE TABLE IF NOT EXISTS `cdr` (
`gid` bigint(20) NOT NULL AUTO_INCREMENT,
`prefix` varchar(20) NOT NULL DEFAULT '',
`id` bigint(20) NOT NULL,
`start` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`clid` varchar(80) NOT NULL DEFAULT '',
`duration` int(11) NOT NULL DEFAULT '0',
`service` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`gid`),
UNIQUE KEY `id` (`id`,`prefix`),
KEY `start` (`start`),
KEY `clid` (`clid`),
KEY `service` (`service`)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8 ;
and this is my query :
SELECT * FROM `cdr`
WHERE
service = 'test' AND
`start` >= '2014-02-09 00:00:00' AND
`start` < '2014-02-10 00:00:00' AND
`duration` >= 10
Date period could be various from 1 hour to maybe 60 day or even more.(like :
DATE(start) BETWEEN '2013-02-02 00:00:00' AND '2014-02-03 00:00:00'
)
The result set has about 150,000 rows for every day. When i try to get result for bigger period or even one day database crashes.
Does anybody have any idea ?
I don't know how to prevent it from crashing, but one thing that I did with my large tables was partition them by date.
Here, I partition the rows by date, twice a month. As long as your query uses the partitioned column, it will only search the partitions containing the key. It will not do a full table scan.
CREATE TABLE `identity` (
`Reference` int(9) unsigned NOT NULL AUTO_INCREMENT,
...
`Reg_Date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`Reference`),
KEY `Reg_Date` (`Reg_Date`)
) ENGINE=InnoDB AUTO_INCREMENT=28424336 DEFAULT CHARSET=latin1
PARTITION BY RANGE COLUMNS (Reg_Date) (
PARTITION p20140201 VALUES LESS THAN ('2014-02-01'),
PARTITION p20140214 VALUES LESS THAN ('2014-02-14'),
PARTITION p20140301 VALUES LESS THAN ('2014-03-01'),
PARTITION p20140315 VALUES LESS THAN ('2014-03-15'),
PARTITION p20140715 VALUES LESS THAN (MAXVALUE)
);
So basically, you just do a dump of the table, create it with partitions and then import the data into it.
I need help for a simple question ,
$tme = date("Y-m-j H:i:s");
mysql_query("DELETE FROM PM_TABLE WHERE date <= $time - INTERVAL 60 SECOND");
So, It should work and delete all records old as long as long 1 minute.
But it cannot do the operation.
returning value would be like this :\
DELETE FROM PM_TABLE WHERE date <= 2011-07-28 08:49:29 - INTERVAL 60 SECOND
table schema :
CREATE TABLE IF NOT EXISTS `PM_TABLE` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`text` varchar(255) COLLATE utf8_bin NOT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
The PHP variable is getting injected as a string, without single quotes to delimit it for SQL to interpret it correctly. But you don't need the PHP function - use:
mysql_query("DELETE FROM PM_TABLE
WHERE date <= NOW() - INTERVAL 60 SECOND");