How to use DATEDIFF? How can I make this to work? or should I use DATEDIFF completly differently?
SELECT DATEDIFF('Started ','will_end') AS 'Duration' FROM my_table WHERE id = '110';
I try to get answer, how many days are inside of two dates.
I would like to get an aswer like:
Duration = 7 days;
I have this kind of database:
Started | will_end
2009-12-17 | 2009-12-24
2009-12-12 | 2009-12-26
Put will_end first, started second:
SELECT DATEDIFF('2009-12-24', '2009-12-17')
---
7
Also, remove the single quotes from your field names:
SELECT DATEDIFF(will_end, started) AS Duration
FROM my_table
WHERE id = 110
, or replace them with the backticks:
SELECT DATEDIFF(`will_end`, `started`) AS `Duration`
FROM `my_table`
WHERE `id` = 110
Are you getting a NULL result? You have the column names in single quotes in your query, which means you are passing the strings 'Started ' and 'will_end' to DATEDIFF rather than the column values. Try removing the single quotes, and you will start to see some results:
SELECT DATEDIFF(Started, will_end) AS Duration FROM my_table WHERE id = '110';
Note that this will give you a negative result. To get a positive result, reverse the order of the columns:
SELECT DATEDIFF(will_end, Started) AS Duration FROM my_table WHERE id = '110';
replace the order
DATEDIFF('will_end','Started')
I think there are 3 parameter to be passed in
DATEDIFF ( datepart , startdate , enddate )
so your code would be
DATEDIFF ( dd , 'Started ','will_end' )
http://msdn.microsoft.com/en-us/library/ms189794.aspx
Related
Well I have a weird problem with MySQL.
I have a table like this :
# table_name #
==============
ID | DATE | RESULT_DATE
When I do
SELECT * FROM table_name
the output show me the table_name.RESULT_DATE as NULL or if there is a date, it show me the date.
BUT, when I do something like this :
SELECT * FROM table_name WHERE DATE BETWEEN '2017-05-03' AND '2017-05-08'
the output show me the table_name.RESULT_DATE as 00-00-0000 for ALL the elements, if they were NULL or if they had a Date element...
Why is this happening?
Thanks
You forgot the quotes around the dates
SELECT * FROM table_name WHERE DATE BETWEEN '2017-05-03' AND '2017-05-08'
here------------------^----------^-----^----------^
I have a problem with data in MySQL.
I have a column "vacation_period" where I keep data with dates separated by commas eg. "02/10/2015,02/11/2015" and I want to explode commas, month and year. I want to make condition where I can compare month and year sent by POST with exploded data from MySQL field.
Example query:
SELECT *
FROM ag_vacations INNER JOIN
ag_employees
ON ag_vacations.user_id = ag_employees.e_id
where ag_vacations.user_id = 1 AND
ag_vacations.vacation_period = 2015 AND
ag_vacations.vacation_period = 02
order by date_added desc
So try this way:
SELECT *
FROM ag_vacations INNER JOIN
ag_employees
ON ag_vacations.user_id = ag_employees.e_id
where ag_vacations.user_id = 1 AND
((ag_vacations.vacation_period REGEXP '[0-9]{2}\/[0-9]{2}\/2015\,[0-9]{2}\/[0-9]{2}\/[0-9]{4}' AND
ag_vacations.vacation_period REGEXP '02\/[0-9]{2}\/[0-9]{4}\,[0-9]{2}\/[0-9]{2}\/[0-9]{4}')
OR (ag_vacations.vacation_period REGEXP '[0-9]{2}\/[0-9]{2}\/[0-9]{4}\,[0-9]{2}\/[0-9]{2}\/2015' AND
ag_vacations.vacation_period REGEXP '[0-9]{2}\/[0-9]{2}\/[0-9]{4}\,02\/[0-9]{2}\/[0-9]{4}'))
order by date_added desc
so if you need to check just first date in that string 02/10/2015,02/11/2015 - you could delete OR part:
OR (ag_vacations.vacation_period REGEXP '[0-9]{2}\/[0-9]{2}\/[0-9]{4}\,[0-9]{2}\/[0-9]{2}\/2015' AND
ag_vacations.vacation_period REGEXP '[0-9]{2}\/[0-9]{2}\/[0-9]{4}\,02\/[0-9]{2}\/[0-9]{4}')
While a string of dates is not ideal, we sometimes receive data this way. If you need to query this before you have the opportunity to clean up your schema, and if your date formats are consistent, you can query the string with like. In this query, we will concat commas to the beginning and end of the ag_vacations.vacation_period column to make sure we are getting the beginning of the date for month and the end of the date for year:
SELECT *
FROM ag_vacations INNER JOIN
ag_employees
ON ag_vacations.user_id = ag_employees.e_id
where ag_vacations.user_id = 1 AND
concat(ag_vacations.vacation_period,',') like '%/2015,%' AND
concat(',',ag_vacations.vacation_period like '%,02/%'
order by date_added desc
If you just want to find the row, you don't need to explode in php.You can use FIND_IN_SET
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
I have a database table like:
id name date price
1 a 2014-05-12 10
2 a 0000-00-00 20
3 a 2014-05-13 30
I want to search by date, and if the date exists, return the price of the date.
if the date does not exist, return the price of date 0000-00-00.
For example:
search by date:2014-05-12, return `10`
search by date:2014-05-20, return `30`
I have tried:
select price from table where (date=table.date or table.date='0000-00-00')
but it does not work.
How do I write the correct query?
Here is one method that uses order by and limit:
select t.price
from table t
where t.date in ('0000-00-00', #date)
order by t.date desc
limit 1;
Note that I changed the parameter name from date to #date to distinguish it from the column with the same name.
The syntax should table table.field (e.g. table.date), while in your example you have field.field (price.date).
Try:
select price from table where (table.date='{$date}' or table.date='0000-00-00')
Note that $date is a variable (assuming you use PHP). If you don't use PHP, you can't just write date as a variable here, but you can use #date.
Get the value of the field to be searched.Let it be $date_search.
if(!empty($date_search)) {
$sql = 'select price from table where date ='.$date_search;
mysql_query($sql);
}
else {
$sql = 'select price from table where date ="0000-00-00"';
mysql_query($sql);
}
I have no idea how can I find the lowest string in date-type
I will just find lowest month(by years in a table)
TableName
Id | M | D | Y |
=======================
1 | 01 | 22 | 2012 |
2 | 11 | 29 | 2012 |
3 | 12 | 30 | 2013 |
4 | 01 | 30 | 2011 | <--- this !
5 | 12 | 14 | 2012 |
PHP:
$sql = "SELECT * FROM TableName WHERE M=?? AND Y=??";
$selected = mysql_query($sql);
so $selected should give me a result like "4/01/30/2011" (Id,M,D,Y)
Any?
SELECT min(concat(Y,M,D)) FROM TableName
Edit: This just looks nice and clean but it is kind of very bad answer, so please use this answer
Just use the ORDER BY clauses:
SELECT * FROM TableName
ORDER BY Y ASC, M ASC, D ASC
More info here : http://www.tizag.com/mysqlTutorial/mysqlorderby.php
bugwheels94's answer will give you the correct result:
SELECT min(concat(Y,M,D))
FROM `TableName`
but this will be unable to use any index you have on any of the date's constituent fields, so will have to visit every row in the table to determine the minimum value.
Combining m4t1t0 and koopajah's answers gives you:
SELECT *
FROM `TableName`
ORDER BY Y, M, D
LIMIT 1
This will be able to use an available index on Y, and maybe even a combined index on (Y,M,D) which can perform much faster on larger tables.
All this being said; It's almost criminal to put an answer to this question that doesn't suggest using a date field instead of your three column setup. The only reason I can think of to separate a date column would be for performance on niche queries that require separate indexes on day or month, but the choice of accepted answer suggests to me that this isn't the case.
As pointed out by Lucius.. If it's a date, store it as a date and run:
SELECT MIN(`DateColumnName`) FROM `TableName`
As a bonus this will give you access to all the MySQL Temporal functions on the column, including the ability to extract day and month, format it how you like and a single field to index and order by.
Please, do yourself a favour and use a date field instead.. you'll save yourself a lot of troubles.
ALTER TABLE `TableName` ADD `date` DATE NOT NULL;
UPDATE `TableName` SET `date` = CONCAT( `Y` , '-', `M` , '-', `D` );
then you'll be able to do:
SELECT MIN(`date`) FROM `TableName`
Simply perform a query ordering by year, month and day and limit your result to the first row.
SELECT * FROM TableName ORDER BY Y, M, D ASC limit 1;
Try this:
SELECT MIN(ColumnName) FROM TableName;
In your case, that would be:
SELECT MIN(Y) FROM TableName;
I am giving you some idea for your query. Kindly follow that :
$sql="SELECT * FROM tbl_name ORDER BY Y, M, D ASC limit 1;
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
$date=$row["id"]."/".$row["M"]."/".$row["D"]."/".$row["Y"];
echo $date;
I hope It will help you
SELECT concat(Y,M,D) FROM TableName
ORDER BY Y ASC, M ASC, D ASC
Limit 1
That way you can return the whole row by replacing "concat(Y,M,D)" with * and easily adapt for different use cases. You could e.g. return the last date row inside the first year by:
SELECT * FROM TableName
ORDER BY Y ASC, M DESC, D DESC
Limit 1
Storing as DATETIME and using native MySQL sorting speeds it up a lot. If you need to keep the seperate values (for whatever reason, e.g. import/export with other systems out of your scope), maybe you can just add another value to the table and synchronise the values?
i want to output the result based on todays date.
the problem is, the output only show 1 result?
database report table:
id | r_amount | id_therapist | date | time | t_tanning | t_deep
// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")
// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
// (1) echoing all result from database
echo $r['r_amount'].'<br>';
// (2) echoing only 1 result????
echo $r['totalProTan'].'<br>';
endwhile;
If the date field is of type datetime, you'll have to do something like
SELECT ... WHERE DATE(date)=CURDATE()
Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.
Try adding a GROUP BY statement to the second SQL statement.
you should group by the key of the elemnts you want to be shown in the end result
The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.
To see the result for many groups of values you have to add a group by clause.