My query currently gets yesterdays data but I now want to get all of last months data. (E.g.from 1st to 31st)
$res = mysql_query("SELECT
FROM_UNIXTIME( enquiry_time ), `id` ,
`fullname` , `address1` , `citytown` ,
`postcode` , `telno` ,
`property_value` ,`total_secured_debt`
, `email` , `on_market` , `agent` ,
`reason` , `price_concession` ,
`asking_price` , `form_page` FROM
$table WHERE TO_DAYS(FROM_UNIXTIME( enquiry_time )) = (TO_DAYS(NOW())-1)
");
There is not a TO_MONTHS so im not sure where to start!
Try:
$res = mysql_query("
SELECT FROM_UNIXTIME(`enquiry_time`), `id`, `fullname`, `address1`,
`citytown`, `postcode`, `telno`, `property_value`, `total_secured_debt`,
`email`, `on_market`, `agent`, `reason`, `price_concession`,
`asking_price`, `form_page`
FROM $table
WHERE YEAR(FROM_UNIXTIME(`enquiry_time`)) = YEAR(CURDATE() - INTERVAL 1 MONTH)
AND MONTH(FROM_UNIXTIME(`enquiry_time`)) = MONTH(CURDATE() - INTERVAL 1 MONTH)
");
This would all work vastly better and faster if enquiry_time were a native DATE or DATETIME field, with an index, instead of a Unix timestamp.
Looking for function MONTH?
That will work (like your TO_DAYS does now), but remember you may be paying a hefty performance price if the table is large: MySQL can't use an index when the WHERE condition depends on a function rather than directly on the indexed column (use EXPLAIN to see the query plan and confirm that this is the case). Performance-wise, you're better off computing the lower and upper bound of the times you want to see (with functions and arithmetic on NOW()) and then using a straight BETWEEN in your WHERE. Again, use EXPLAIN to double check -- trying to second guess MySQL's query optimizer is a sterile exercise, it's much easier to check on what it plans to do;-).
Could you use something like the following? I think it will get you what you want.
FROM_UNIXTIME(enquiry_time)
BETWEEN date_format(NOW() - INTERVAL 1 MONTH, '%Y-%m-01')
AND last_day(NOW() - INTERVAL 1 MONTH)
Here's the reference.
While chaos's answer will work, if $table is indexed by enquiry_time,
then it will be faster to compare against that field directly than against a function of it.
That transforms his answer into the even uglier:
$res = mysql_query("
SELECT FROM_UNIXTIME(enquiry_time), id, fullname, address1,
citytown, postcode, telno, property_value, total_secured_debt,
email, on_market, agent, reason, price_concession, asking_price,
form_page
FROM $table
WHERE enquiry_time >= UNIX_TIMESTAMP(concat(year(curdate() - interval 1 month), '-', month(curdate() - interval 1 month), '-01'))
AND enquiry_time < UNIX_TIMESTAMP(concat(year(curdate()), '-', month(curdate()), '-01'))
");
i see you are using php so this might be better than wrestling with mysql functions:
$end_of_month = strtotime(date('Y-m-01 00:00:00'))-1;
$start_of_month = strtotime(date('Y-m-01 00:00:00',$end_of_month));
$res = mysql_query("SELECT
FROM_UNIXTIME( enquiry_time ), `id` ,
`fullname` , `address1` , `citytown` ,
`postcode` , `telno` ,
`property_value` ,`total_secured_debt`
, `email` , `on_market` , `agent` ,
`reason` , `price_concession` ,
`asking_price` , `form_page` FROM'
$table WHERE enquiry_time >= '".$start_of_month."' AND enquiry_time <= '".$end_of_month."'
");
Related
I have this query:
SELECT id
, order_date
, seat_number
, cashier_fk
, branch_fk
, waiter_fk
, void
, total_amount
, customer_name
, payment
, notes
, down_payment
, received_date
, void_reason
, discount
, discount_percentage
, printed
, done
, vat
, service_charge
FROM order_tbl
WHERE received_date between "2018-03-15" AND "2018-03-18"
but it shows
My table has this record:
id-------order_date
1-------2018-03-09 09:09:25
2-------2018-03-13 18:29:16
3-------2018-03-13 20:00:49
4-------2018-03-13 20:01:46
5-------2018-03-13 20:05:48
6-------2018-03-13 20:06:34
7-------2018-03-13 20:07:15
9-------2018-03-16 19:06:23
10-------2018-03-16 20:22:26
But it shows only
id-------order_date
5-------2018-03-13 20:05:48
6-------2018-03-13 20:06:34
7-------2018-03-13 20:07:15
9-------2018-03-16 19:06:23
10-------2018-03-16 20:22:26
What is wrong with my query?
Do not use between with dates or date/times. The time component throws everything off.
Instead, express the logic as:
WHERE received_date >= '2018-03-15' AND
received_date < '2018-03-19'
Note the inequality at the end of the range. This ensures that you get everything from that date.
Aaron Bertrand has a really good blog post on the subject, What do BETWEEN and the devil have in common?.
I have to select some rows where the date is today or higher and I can select only the registers where the time is ten minutes before the current time. My doubt is on how to do that with 'datetime' type. Down below is the query:
SELECT
GROUP_CONCAT(timee.nome_time
ORDER BY timee.nome_time
SEPARATOR ' X ') AS nome_time,
partida.id,
DATE_FORMAT(partida.data_hora, '%d/%m/%Y %H:%i') AS data_hora,
partida.tb_cotacao_id
FROM
tb_partida AS partida,
tb_time AS timee,
tb_partida_time AS partidaTime
WHERE
(partida.id = tb_partida_id
&& timee.id = tb_time_id)
AND (partida.flag_ativo = 1
AND partida.flag_cancelado <> 1
AND partida.flag_finalizado <> 1)
AND partida.tb_campeonato_id = 11
GROUP BY partida.id
I'd really appreciate any help. Thanks in advance.
Use the TIME_TO_SEC(TIMEDIFF(now(),<datetime_field>) to get the time difference and convert it to seconds. For greater than 10 minutes it will be something like this
SELECT ... FROM .. WHERE TIME_TO_SEC( TIMEDIFF( now() , tb_time )) > 600 ...
EDIT
To get the rows that has time 10 minutes more than current time, just reverse the parameters inside the TIMEDIFF. ie.,
SELECT ... FROM .. WHERE TIME_TO_SEC( TIMEDIFF(tb_time, now() )) > 600 ...
I have login table with DOB Column. I need duplicate column for age. But i can't do this. I can convert DOB column convert to Age for alone
`SELECT FLOOR(DATEDIFF(DAY,'10/10/1990' , getdate()) / 365.25)` works fine.
But I need to convert whole column.
If I'm Using
SELECT FLOOR(DATEDIFF(DAY,Select DOB From login_tbl , getdate()) / 365.25) like this,
It's throwing error. How can I get it?
Thankyou
Your approach will get wrong result in such cases below:
declare #now date
set #now = '11/10/2014'
select
FLOOR(DATEDIFF(DAY,'11/10/2013' , #now) / 365.25) -- should be 1 but will get 0
, FLOOR(DATEDIFF(DAY,'11/10/2012' , #now) / 365.25) -- should be 2 but will get 1
, DATEDIFF(DAY,'11/10/2013' , #now)
, DATEDIFF(DAY,'11/10/2012' , #now)
My suggestion is :
declare #now date
set #now = '11/10/2014'
select (convert(int,convert(varchar(8), #now ,112))
- convert(int,convert(varchar(8),convert(date,'11/10/2013'),112) ) )/10000
You could see my explain in this answer.
So for your login_tbl you could:
select
DOB, (convert(int,convert(varchar(8), DOB ,112))
- convert(int,convert(varchar(8),convert(date,'11/10/2013'),112) ) )/10000 as AGE
from
login_tbl
select trunc((trunc(sysdate) - to_date('16-mar-2010', 'dd-mon-yyyy'))/ (365.23076923074))
from dual
I have 1 query as given below where a parameter with name "ListOfDate" which is coming by front end in form of string..i have "ENCOUNTERDATE" in mysql with datetime datatype..
SELECT d.encounterdate,
d.hospitalid,
amiop1,
amiop2,
amiop3,
amiop4,
amiop5,
amiop16
FROM factopami f,
dimpatientencounter d
WHERE d.hospitalid = 987654
AND d.measurecategory = 'AMI'
AND ( encounterdate IN ( ** listofdate ** )
OR encounterdate IS NULL )
AND d.patientid = f.patientid
AND d.id = f.patientencounterid
ORDER BY encounterdate;
after it i tried to convert ListOfDate into date:
SELECT d.encounterdate, d.hospitalid, amiop1, amiop2, amiop3, amiop4,
amiop5, amiop16
FROM factopami f, dimpatientencounter d
WHERE d.hospitalid = 987654
AND d.measurecategory = 'AMI'
AND ( encounterdate IN (str_to_date ('01-10-2012' '%m-%d-%Y'))
OR encounterdate IS NULL
)
AND d.patientid = f.patientid
AND d.ID = f.patientencounterid
ORDER BY encounterdate;
which is working for single string ...but i got list of string which is giving me error..
SELECT d.encounterdate,
d.hospitalid,
amiop1,
amiop2,
amiop3,
amiop4,
amiop5,
amiop16
FROM factopami f,
dimpatientencounter d
WHERE d.hospitalid = 987654
AND d.measurecategory = 'AMI'
AND ( encounterdate IN ( Str_to_date('01-10-2012', '01-10-2012',
'%m-%d-%Y') )
OR encounterdate IS NULL )
AND d.patientid = f.patientid
AND d.id = f.patientencounterid
ORDER BY encounterdate;
LIMIT 0, 1000 Error Code: 1582. Incorrect parameter count in the call to native function 'STR_TO_DATE' 0.000 sec
so how can i convert it to on mysql level
In short - at the moment you're converting the list to:
(encounterdate IN ( STR_TO_DATE('01-10-2012','01-10-2012', '%m-%d-%Y'))
Instead, you need to convert it to:
( encounterdate IN ( STR_TO_DATE('01-10-2012', '%m-%d-%Y')
, STR_TO_DATE('01-10-2012', '%m-%d-%Y') )
As more of an explanation, the IN operator is expecting a list of things:
encounterdate IN ( thing1, thing2, thing3 )
The thing you are passing is a date, meaning you're doing this:
encounterdate IN ( date1, date2, date3 )
Alas, you have strings instead of dates, and so you need to convert each of those strings into dates. Thus you need to some conversions.
date1 needs to be STR_TO_DATE( string1, '%m-%d-%y )
date2 needs to be STR_TO_DATE( string2, '%m-%d-%y )
date3 needs to be STR_TO_DATE( string3, '%m-%d-%y )
Putting that all together, you need to generate:
encounterdate IN ( STR_TO_DATE('01-10-2012', '%m-%d-%Y')
, STR_TO_DATE('01-10-2012', '%m-%d-%Y')
, STR_TO_DATE('01-10-2012', '%m-%d-%Y')
As an alternative, if you feel it's not possible to produce this, you could flip the conversion round and instead convert the encounterdate column to a string using DATE_FORMAT as you do the comparison.
Documentation here:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
http://www.w3schools.com/sql/func_date_format.asp
This would result in:
DATE_FORMAT( encounterdate, '%m-%d-%Y' ) IN ( '01-10-2012'
, '01-10-2012'
, '01-10-2012' )
However, you should bear in mind that this will have an impact on the indexing of encounterdate, though this might not be a problem in your use-case.
As it is explained in mysql manual, str_to_date function , get only to parameters. The first parameter is your date string, and the second one is the format of your date string.so you cann't use it like this:
STR_TO_DATE('01-10-2012','01-10-2012', '%m-%d-%Y')
You should use this:
STR_TO_DATE('01-10-2012', '%m-%d-%Y'),STR_TO_DATE('01-10-2012', '%m-%d-%Y')
I have this part of a query:
(#tmpo1245 := CAST( ( ( pm5.`meta_value` - pm4.`meta_value` ) / 86400 ) AS SIGNED ) ) AND
(#mutdate:=DATE_SUB( '2011-06-1', INTERVAL #tmpo1245 DAY ) ) AND
Which is causing my query to fail. I know CAST( ( ( pm5.meta_value- pm4.meta_value) / 86400 ) AS SIGNED ) is 5, I put it in a select statement to test it. I also know the following query works just fine:
(#tmpo1245 := 5 ) AND
(#mutdate:=DATE_SUB( '2011-06-1', INTERVAL #tmpo1245 DAY ) ) AND
What is going on?
It seems the error is with the clause inside the CAST in your query. I guess the data types of pm5.meta_value and pm4.meta_value your are trying to subtract are not numeric. Hence please cast them decimals first before subtracting. Example code would be as follows.
#tmpo1245 := CAST( ( (
CAST( pm5.`meta_value` AS DECIMAL) - CAST( pm4.`meta_value` AS DECIMAL)) / 86400 )
AS SIGNED )