retrieve mysql data using 3 columns - php

for example i have 3 fields in my search DAY, MONTH, YEAR
the user must select it independently or all together like
DAY/MONTH
DAY/YEAR
MONTH/YEAR
DAY/MONTH
DAY/MONTH/YEAR
inputs: day month year
method: GET
select must search in any column with all combinations
table
id | day | month | year
---------------------------------------
1 | 10 | jan | 2013
2 | 25 | jun | 2013
3 | 02 | jan | 2015
SELECT * FROM mytable WHERE day = $day or month = $month or year = $year;
if my month = jan should return 1 and 3
if my my day = 10 and year = 2013 should return 1
and so on
it doesn't work... it only matches with one column

You are probably facing a problem with NULL values. This may be what you want:
SELECT *
FROM mytable
WHERE ($day is null or day = $day) and
($month is null or month = $month) and
($year is null oryear = $year);
This assumes that "missing" values are NULL. You may have some other representation (say an empty string), in which case change the logic accordingly.

Related

How to delete database entries with one query < actual date with year month and day value in separate fields?

I have a mysql db with 3 fields in table (year, month, day) which represents dates
year | month | day
2019 | 10 | 24
2018 | 5 | 4
2018 | 8 | 23
Now I want to delete all entries in db smaller than actual month and year.
Is that possible within one mysql query and how?
I tried ...
"DELETE FROM db WHERE year < ".date("Y")." AND month < ".date("m");
But that leaves some entries in DB for example 2018-11-28
Any ideas?
You can do this purely in SQL:
DELETE FROM db WHERE (year < YEAR(NOW())) or (year = YEAR(NOW()) AND month < MONTH(NOW()))
If the year is 2018 or less or if the year is 2019 and the month is less than August it will delete all records.
"DELETE FROM db WHERE year < ".YEAR(getdate())." AND month < ".MONTH(getdate());
YEAR(getdate()) will get you the current year
MONTH(getdate()) will get you the current month

Get month difference only if the days are the same

How can I get the difference of months between two dates in MySQL only if the days are the same? Here is what i have so far but it doesn't work because when the days are not the same, it still works:
TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')
Output: 1
TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-22')
Output: 1 // should NOT work because days are 05 and 22. Needs to be the same dates
I can obviously do:
DAY('2019-05-05') = DAY('2019-06-05') AND TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')
but how can I do it in one function?
Thanks!
SUBDATE()/ADDDATE/DATE_SUB/DATE_ADD will handle this well:
SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05'
| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05' |
| ------------------------------------------------------: |
| 0 |
SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22'
| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22' |
| ------------------------------------------------------: |
| 1 |
See the DBfiddle
In MySQL, you can get it by using the below query...
select DATEDIFF('2019-06-22', '2019-05-05') as Diff from table_name where
day('2019-06-22') == day('2019-05-05');
using column name...
select DATEDIFF(dateColum2, dateColum1) as Diff from table_name where
day(dateColum2) == day(dateColum1);
From PHP you can get it like below...
$dateValue1 = '2019-05-05';
$dateValue2 = '2019-06-22';
$time1=strtotime($dateValue1);
$day1=date("D",$time1);
$time2=strtotime($dateValue2);
$day2=date("D",$time2);
if($day1 == $day2 ) {
$seconds_diff = $time2 - $time;
}

How to check given date period is between two dates in MySQL and PHP

I have a travel history of the employee. I want to check, for the particular month, whether he is in outstation (traveled outside) or in the office, to calculate number of hours in travel. Just we are maintaining the travel database, in that we entered employee name with client place traveled with travel date and returned date.
One employee have the following data:
Traveled date: '2015-08-29' (29th Aug 2015)
returned date: '2015-11-06' (6th Nov 2015)
So here, I want to check in the month of October, all employees that are out of the office. Obviously this guy should come in that category, but I could not get him.
I also tried directly in MySQL workbench, but I didn't get the result.
My original PHP code:
// $req['date_start'] = '2015-10-01'
// $req['date_end'] = '2015-10-31'
$employeeTravel = new EmployeeTravelRecord();
$TravelEntryList = $employeeTravel->Find("(travel_date between ? and ? or return_date between ? and ? )",array($req['date_start'], $req['date_end'],$req['date_start'], $req['date_end']));
$startdate = $req['date_start'];
$enddate = $req['date_end'];
foreach($TravelEntryList as $Travelentry){
$key = $Travelentry->employee;
if($startdate >= $Travelentry->travel_date)
{
$firstdate = $startdate;
}
else
$firstdate = $Travelentry->travel_date;
if($enddate <= $Travelentry->return_date )
{
$lastdate = $enddate;
}
else
$lastdate = $Travelentry->return_date;
$holidays = $this->getholidays($firstdate,$lastdate);
$totalhours = $this->getWorkingDays($firstdate,$lastdate,$holidays); //It returns in total time of outstation in hours excluding company holidays
$amount = $totalhours;
if(isset($TravelTimeArray[$key])){
$TravelTimeArray[$key] += $amount;
}else{
$TravelTimeArray[$key] = $amount;
}
}
But my input data doesn't retrieve that particular employee record, because both traveled date and returned date don't fall in my input dates.
MySQL Workbench:
SELECT * FROM employeetravelrecords where travel_date between '2015-10-01' and '2015-10-31' or return_date between '2015-10-01' and '2015-10-31';
I got only the following result:
+----+----------+---------------+----------------+----------+------------------+------------------+----------------+
| id | employee | type | project | place | travel date | return date | details |
+----+----------+---------------+----------------+----------+------------------+------------------+----------------+
| 13 | 38 | International | PVMTC Training | Hongkong | 11/10/2015 13:33 | 28/11/2015 13:33 | PVMTC Training |
| 14 | 48 | International | PVMT | VIETNAM | 10/10/2015 9:28 | 1/1/2016 9:28 | PETRO |
| 17 | 57 | International | PVMT | Saudi | 10/10/2015 11:39 | 2/1/2016 11:39 | |
+----+----------+---------------+----------------+----------+------------------+------------------+----------------+
The following record didn't get retrieved by this query:
+---+----+---------------+------+-----+-----------------+-----------------+-----------------+
| 7 | 22 | International | MOHO | XYZ | 29/8/2015 18:00 | 6/11/2015 18:00 | FOR DDS review |
+---+----+---------------+------+-----+-----------------+-----------------+-----------------+
SELECT * FROM employeetravelrecords
WHERE
return_date >= '2015-10-01' /* start parameter */
and travel_date <= '2015-10-31' /* end parameter */
The logic seems a little mind-bending at first and I've even reordered the comparisons a little from my original comment above. Think of it this way: you need to return after the start of the range and leave before the end of the range in order to have an overlap.
For a longer explanation and discussion you might find this page useful: TestIfDateRangesOverlap
SELECT '2015-08-29' < '2015-10-31' AND '2015-11-06' >= '2015-10-01' on_leave;
+----------+
| on_leave |
+----------+
| 1 |
+----------+
You can use between for get data between two dates. Here is the working example.
Here is my table structure :
Table User
user_id user_name created_date modified_date
1 lalji nakum 2016-01-28 17:07:06 2016-03-31 00:00:00
2 admin 2016-01-28 17:25:38 2016-02-29 00:00:00
And here is my mysql query :
Query
SELECT * FROM `user` WHERE created_date between '2015-12-01' and '2016-12-31' or modified_date between '2015-12-01' and '2016-12-31'
Result of above query :
Result
user_id user_name created_date modified_date
1 lalji nakum 2016-01-28 17:07:06 2016-03-31 00:00:00
2 admin 2016-01-28 17:25:38 2016-02-29 00:00:00
You want to find all those people who are not available for the complete duration say between T1 & T2 (and T2 > T1). The query you used will only give users whose start date and return date both lie between the given interval which is not the required output.
So to get the desired output you need to check for all employees who have started their journey on or before T1 and return date is on or after T2 (thus unavailable for complete interval [T1, T2]). So the query you can use is:
SELECT * FROM employeetravelrecords where travel_date <= '2015-10-01' and return_date >= '2015-10-31';
If you want employees who are even partially not available between the given duration then we need employees who started their travel before T1 and have any return date later than T1 (thus making them atleast unavailable for a part of the given interval):
SELECT * FROM employeetravelrecords where travel_date <= '2015-10-01' and return_date > '2015-10-01';

MySQL query to retrieve maximum number of items within a given time period

I've a table like attached.
I want to find the "number of items in a certain month which has maximum entries in the database".
For instance, Jan has 10 entries, Feb has 13 entries, Mar has 8 entries.
I want to find the the number 13 for Feb from the database as it has the max entries. How do I check the time range in the query?
You can group all of your realeasedates by month and year to get a count like this:
SELECT MONTH(releasedate) AS month, YEAR(releasedate) as year, count(r_id) AS number
FROM my_table
GROUP BY YEAR(releasedate), MONTH(releasedate)
ORDER BY YEAR(releasedate), MONTH(releasedate)
This'll give you something like this:
+--------+--------+--------+
| month | year | number |
+--------+--------+--------+
| 1 | 2013 | 13 |
| 2 | 2013 | 8 |
Then you could select the maximum like this:
SELECT MONTH(releasedate) AS month, YEAR(releasedate) as year, count(r_id) AS number
FROM my_table
GROUP BY YEAR(releasedate), MONTH(releasedate)
ORDER BY count(r_id)
LIMIT 1
Which'll give you:
+--------+--------+--------+
| month | year | number |
+--------+--------+--------+
| 4 | 2013 | 19 |
+--------+--------+--------+
Which'll represent the highest month
SELECT COUNT(*) FROM `mytable` WHERE releasedate >= DATE '2013-02-01' AND releasedate <= DATE '2013-02-28'
That should work
EDIT:
As suggested by lafor...
WHERE YEAR(releasedate)=2013 AND MONTH(releasedate)=2
should also work

Select dates between this monday and this friday

I have a table with a date field (2013-07-11 = July 11th, 2013).
I need to select entries from the monday (the start of my week) of any given week until the end of that week.
I've seen queries that can grab rows whose date is 1 week ago, but I specifically need to grab rows that have a date field that occurs this week, regardless of what the current day of the week is.
I'm currently grabbing it in php using this, but I feel like there has to be a mysql method for calculating the beginning and end of this week:
$this_monday = date('Y-m-d', strtotime('previous monday'));
$this_friday = date('Y-m-d',strtotime('this friday'));
$sql = "SELECT `date`, $sign FROM `horoscopes`
WHERE `date` >= '$this_monday' AND `date` <= '$this_friday'
AND type = 'Daily'
ORDER BY `date` ASC
";
And I'm pretty sure that on monday it will end up grabbing monday of last week, not monday.
from this data set I'd like to select the following:
+------------+
| date |
+------------+
| 2013-07-12 |
| 2013-07-11 |
| 2013-07-10 |
| 2013-07-09 |
| 2013-07-17 |
| 2013-07-08 |
| 2013-07-05 |
+------------+
7-8, 7-9, 7-10, 7-11, 7-12 regardless of the day of the week.
Just learned about the WEEK() function in mysql
SELECT `date` FROM horoscopes WHERE WEEK(`date`) = WEEK(NOW(), -1);

Categories