I am attempting to query for a record. The date is stored as a date time stamp and my query looks like this:
SELECT count(c.id) as totalOrders
FROM Cart c
WHERE c.artist_id = 1
AND c.paid = 1
AND date_format(c.created, 'Y-m-d') between '2016-09-06' AND '2016-09-07'
My date time stamp is this: 2016-09-07 21:04:46
For some reason this does not return any records, why?
Change the following line:
AND date_format(c.created, 'Y-m-d') between '2016-09-06' AND '2016-09-07'
to
AND date(created) between '2016-09-06' AND '2016-09-07'
date() function will return the date from datetime and it will check in the given range.
use date() function instead of date_format()
SELECT count(c.id) as totalOrders
FROM Cart c
WHERE c.artist_id = 1
AND c.paid = 1
AND date(c.created) between '2016-09-06' AND '2016-09-07'
Related
SELECT c.enddate FROM cohort c ORDER BY c.enddate DESC LIMIT 1
I have a sql query above, it works in database, the result select a date like: '2018-07-18'
I try to use while loop with mysqli_fetch_row in php to fetch this date, but the result will only fetch:
2018
How can I get the whole date?
if ($runquery = $conn->query($result_validation))
{
//get the enddate from the last cohort
while ($row = mysqli_fetch_row($runquery))
{
$lastDate = $row[0];
}
}
$row[0] only display first number: 2018.
Adding DATE() function in the column will convert it to a valid date format like for the example below!
SELECT DATE(c.enddate) FROM cohort c ORDER BY DATE(c.enddate) DESC LIMIT 1
Try SELECT DATE(c.enddate) FROM cohort c ORDER BY c.enddate DESC LIMIT 1,
Try this one
SELECT DATE_FORMAT(c.enddate,"%Y-%m-%d") FROM cohort c ORDER BY c.enddate DESC LIMIT 1
The DATE_FORMAT() function formats a date as specified by a format mask.
I want to make monthly sales from the sales table but i store date data using time() format
Example :
UserID | Product | Date
1 | Hot Dog | 1504363230
4 | Chicken | 1504695631
1 | Potato | 1504761716
3 | Spinach | 1505003789
So, how can i create monthly sales from there without replace Date into date() ? Because it will take a long time if i have to change 300K row
What should i do ?
Select * FROM Sales WHERE UserID = UserID AND Date = ?
the output must be like this
UserID 1 do 2 transaction in the last month or UserID 1 do 3 transaction in this
month
A PHP solution would be to use the second parameter in the date function:
string date ( string $format [, int $timestamp = time() ] )
The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().
You can convert a unix timestamp to a datetime string in MySQL with FROM_UNIXTIME.
SELECT FROM_UNIXTIME(`Date`) as `Datetime` FROM sales
You can then expand on this with other date functions like MONTH or YEAR
SELECT MONTH(FROM_UNIXTIME(`Date`)) as `Month` FROM sales
EDIT:
I think this should work for you. I guess you want to avoid PHP's date() but MySQL's DATE() is okay.
SELECT
COUNT(*) AS nb_transaction,
UserID
FROM
sales
WHERE
DATE(`Date`) LIKE '2018-06-%'
Of course replace the month with the one you are looking for.
SQL (will be faster than PHP):
You can convert any UNIX Timestamp using FROM_UNIXTIME() to any format:
FROM_UNIXTIME(`Date`, '%Y %D %M %h:%i:%s')
PHP:
The time() function returns a UNIX Timestamp.
If you want to display a date using one, you can use DateTime::setTimestamp:
$date = new DateTime();
$date->setTimestamp($row['Date']);
echo $date->format('Y-m-d H:i:s'); // Hot Dog = 2017-09-02 14:40:30
Or shortly:
echo (new DateTime())->setTimestamp($row['Date'])->format('Y-m-d H:i:s');
$timestamp = 1517317337107; $date=date('Y-m-d H:i:s',
$timestamp/1000);
echo "date and time : ". $date."<br>";
$month=date('Y-m-d',$timestamp/1000);
echo "only date : ".$month."<br>";
#output
date and time : 2018-01-30 13:02:17
only date : 2018-01-30
hope this will help
I want to get count of previous day records from database.
I am using following method
$date = date('Y-m-d H:i:s', strtotime('-1 day'));
$users = 'SELECT Count(*) FROM users where date="'.$date.'"';
This is show count 0 as date format in database is (Y-m-d H:i:s).
Thanks.
Could just do
select count(*) from users where to_days(date) = (to_days(now()) - 1);
This is useful if your date column is a datetime - we're just converting to a day number and checking how many records have yesterdays day number.
Hope it will help you
SELECT COUNT(*) FROM users WHERE date = (CURDATE() - INTERVAL 1 DAY)
You might want to consider asking MYSQL itself about it, so that PHP doesn't have to compute it (and it is likely to be faster) :
SELECT Count(*) FROM users WHERE date = DATE_SUB(NOW(), INTERVAL 1 DAY)
I have a list of unix timestamps in a database, and I wanting to select the ones that are from today.
i.e If today is Tueday, I want to get all the timestamps that were made today? Is it possible? Is there such a things as strtotime("Today")?
Any help would be great
you can use mktime() to generate the timestamp for the start of the day and then find the database entries with a timestamp greater than that.
$start = strtotime(date('Y-m-d 00:00:00')); // Current date, at midnight
$end = strtotime(date('Y-m-d 23:59:59')); // Current date, at 11:59:59 PM
then, you can just select where the timestamp is between the above 2 timestamps:
"SELECT FROM `foo` WHERE `timestamp` BETWEEN '{$start}' and '{$end}'"
You can convert the unix timestamps to sql dates in the SQL using FROM_UNIXTIME(), then compare those to NOW()
SELECT * FROM `tablename` WHERE DATE(FROM_UNIXTIME(`dateFld`)) = DATE(NOW());
Check if DAY(NOW()) and MONTH(NOW()) and YEAR(NOW()) is equal to appropriate value of DAY(timestamp) and MONTH(timestamp) and YEAR(timestamp).
select timestamp from table where DAY(NOW()) = DAY(timestamp) AND MONTH(NOW()) = MONTH(timestamp) AND YEAR(NOW()) = YEAR(timestamp)
If you're using mysql:
SELECT * FROM table WHERE DATE(NOW()) = DATE(FROM_UNIXTIME(timestampcol))
FROM_UNIXTIME(somefield) can be compared to CURDATE() assuming you're using MySQL
SELECT * FROM mytable WHERE FROM_UNIXTIME(datefield,'%Y-%m-%d') = CURDATE();
ETA:
Okay, I was assailed by doubt when this answer was marked down. So I went and did a couple of tests. Given MySQL it definitely works. So why the downmod?
Consider this test which outputs 2 identical fields for every row in a table:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE()),'%Y-%m-%d') a , CURDATE() b
FROM tablewithsomerows
WHERE FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE()),'%Y-%m-%d') = CURDATE();
I want to be able to fetch results from mysql with a statement like this:
SELECT *
FROM table
WHERE amount > 1000
But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
...$m being a month but it gave error.
In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?
You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(dateStart) = {$m}
Caveats:
Mind that you are using mysql_escape_string or you risk SQL injection attacks.
Function calls on columns means that an index, if one exists, can not be used
Alternatives:
Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:
WHERE startdate BETWEEN STR_TO_DATE([start_date], [format])
AND STR_TO_DATE([end_date], [format])
See the documentation for formatting syntax.
Reference:
MONTH
YEAR
BETWEEN
STR_TO_DATE
Use the month() function.
select month(now());
Try this:
SELECT *
FROM table
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')
E.g.
$date = sprintf("'%04d-%02d-01'", $year, $month);
$query = "
SELECT
x,y,dateStart
FROM
tablename
WHERE
AND amount > 1000
AND dateStart >= $date
AND dateStart < $date+Interval 1 month
";
mysql_query($query, ...
This will create a query like e.g.
WHERE
AND amount > 1000
AND dateStart >= '2010-01-01'
AND dateStart < '2010-01-01'+Interval 1 month
+ Interval 1 month is an alternative to date_add().
SELECT Date('2010-01-01'+Interval 1 month)-> 2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)-> 2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.
Try this
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(datestart)
GROUP BY EXTRACT(YEAR_MONTH FROM datestart)
Try this if(date field is text then convert this string to date):
SELECT * FROM `table_name` WHERE MONTH(STR_TO_DATE(date,'%d/%m/%Y'))='11'
//This will give month number MONTH(STR_TO_DATE(date,'%d/%m/%Y'))
//If its return 11 then its November
// Change date format with your date string format %d/%m/%Y
Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
Day:
SELECT EXTRACT(DAY FROM "2017-06-15");
Month:
SELECT EXTRACT(MONTH FROM "2017-06-15");
Year:
SELECT EXTRACT(YEAR FROM "2017-06-15");