Searching for availability with MySQL (and PHP)? - php

I have two MySQL (MyIsAm) tables that represent letting units and bookings:
LettingUnits (ID, Name, etc...)
LettingUnitBookings (ID, F_LU_ID, Start, End)
Where F_LU_ID is a foreign key to the unit.
What is the best way to search for units that are available during a certain time frame? The search is passed a Start, End and Duration.
Start = Earliest start of the booking
End = Latest end of the booking
Duration = Duration of the booking
I'd be interested to know if it's even possible to do this in MySQL, however if not then the best way to do it in PHP.
Example
In answer to the answers below I feel an example will help explain the problem.
A LettingUnit:
(123, "Foo Cottage")
Some LettingUnitBookings:
(400, 123, 01/01/09, 05/01/09) - a 5 day booking
(401, 123, 10/01/09, 20/01/09) - a 10 day booking
(402, 123, 25/01/09, 30/01/09) - a 5 day booking
If we search for:
Start = 01/01/09
End = 01/02/09
Duration = 5 (days)
Then we want the unit to show up. Because there is availability for a 5 day booking within the search range.
If the duration is 10 then the unit won't show up as there are no 10 consecutive unbooked days within the search range.

Here's a solution that seems to work:
SELECT t.*, DATEDIFF(t.LatestAvailable, t.EarliestAvailable) AS LengthAvailable
FROM
(SELECT u.*,
COALESCE(b1.End, #StartOfWindow) AS EarliestAvailable,
COALESCE(b2.Start, #EndOfWindow) AS LatestAvailable
FROM LettingUnits u
LEFT OUTER JOIN LettingUnitBookings b1
ON (u.ID = b1.F_LU_ID AND b1.End BETWEEN #StartOfWindow AND #EndOfWindow)
LEFT OUTER JOIN LettingUnitBookings b2
ON (u.ID = b2.F_LU_ID AND b2.Start BETWEEN #StartOfWindow AND #EndOfWindow
AND b2.Start >= b1.End) -- edit: new term
) AS t
LEFT OUTER JOIN LettingUnitBookings x
ON (t.ID = x.F_LU_ID AND x.Start < t.LatestAvailable AND x.End > t.EarliestAvailable)
WHERE x.ID IS NULL AND DATEDIFF(t.LatestAvailable, t.EarliestAvailable) >= #WindowSize;
The output is:
+-----+-------------+-------------------+-----------------+-----------------+
| ID | Name | EarliestAvailable | LatestAvailable | LengthAvailable |
+-----+-------------+-------------------+-----------------+-----------------+
| 123 | Foo Cottage | 2009-01-05 | 2009-01-10 | 5 |
| 123 | Foo Cottage | 2009-01-20 | 2009-01-25 | 5 |
| 456 | Bar Cottage | 2009-01-20 | 2009-01-31 | 11 |
+-----+-------------+-------------------+-----------------+-----------------+
Analyzing this with EXPLAIN shows that it employs indexes pretty well:
+----+-------------+------------+--------+---------------+---------+---------+-------+------+-------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+---------------+---------+---------+-------+------+-------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 9 | Using where |
| 1 | PRIMARY | x | ref | F_LU_ID | F_LU_ID | 8 | t.ID | 2 | Using where; Not exists |
| 2 | DERIVED | u | system | NULL | NULL | NULL | NULL | 1 | |
| 2 | DERIVED | b1 | ref | F_LU_ID | F_LU_ID | 8 | const | 0 | |
| 2 | DERIVED | b2 | ref | F_LU_ID | F_LU_ID | 8 | const | 0 | |
+----+-------------+------------+--------+---------------+---------+---------+-------+------+-------------------------+
Compare with the EXPLAIN report for the solution given by #martin clayton:
+----+--------------+---------------------+--------+---------------+---------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------+---------------------+--------+---------------+---------+---------+------+------+---------------------------------+
| 1 | PRIMARY | lu | system | PRIMARY,ID | NULL | NULL | NULL | 1 | |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 4 | Using where |
| 2 | DERIVED | <derived3> | ALL | NULL | NULL | NULL | NULL | 4 | Using temporary; Using filesort |
| 2 | DERIVED | <derived5> | ALL | NULL | NULL | NULL | NULL | 4 | Using where; Using join buffer |
| 5 | DERIVED | LettingUnitBookings | ALL | NULL | NULL | NULL | NULL | 3 | |
| 6 | UNION | LettingUnitBookings | index | NULL | F_LU_ID | 8 | NULL | 3 | Using index |
| NULL | UNION RESULT | <union5,6> | ALL | NULL | NULL | NULL | NULL | NULL | |
| 3 | DERIVED | LettingUnitBookings | ALL | NULL | NULL | NULL | NULL | 3 | |
| 4 | UNION | LettingUnitBookings | index | NULL | F_LU_ID | 8 | NULL | 3 | Using index |
| NULL | UNION RESULT | <union3,4> | ALL | NULL | NULL | NULL | NULL | NULL | |
+----+--------------+---------------------+--------+---------------+---------+---------+------+------+---------------------------------+
In general, you want to avoid optimization plans that force Using filesort or Using temporary because these are performance killers. A query using GROUP BY is almost certain to cause this kind of optimization, at least in MySQL.

It's not pretty.
Join LettingUnitBookings to itself
Find the start and end of gaps between bookings for each F_LU_ID
Get the size of the gaps - the available 'slots'
Consider the case where there are no existing bookings that 'bracket' a suitable slot, add in outlier dates for this
Join that projection to the LettingUnits table and apply WHERE criteria (start, end, duration)
I've neglected to include BookingUnits that have no bookings at all.
Ends up looking like this:
SELECT #StartOfWindow := '2009-01-01',
#EndOfWindow := '2009-02-01',
#WindowSize := 5
;
SELECT
lu.Name,
Slots.*
FROM (
SELECT
lub1.F_LU_ID,
DATE_ADD( MAX( lub2.date_time ), INTERVAL 1 DAY ) AS StartOfSlot,
DATE_SUB( lub1.date_time, INTERVAL 1 DAY ) AS EndOfSlot,
DATEDIFF( lub1.date_time, MAX( lub2.date_time ) ) - 1 AS AvailableDays
FROM
( SELECT F_LU_ID, Start AS date_time FROM LettingUnitBookings
UNION
SELECT F_LU_ID, CAST( '9999-12-31' AS DATE ) FROM LettingUnitBookings
) AS lub1,
( SELECT F_LU_ID, End AS date_time FROM LettingUnitBookings
UNION
SELECT F_LU_ID, CAST( '1000-01-01' AS DATE ) FROM LettingUnitBookings
) AS lub2
WHERE
lub2.date_time <= lub1.date_time
AND lub2.F_LU_ID = lub1.F_LU_ID
GROUP BY
lub1.F_LU_ID,
lub1.date_time
) Slots
JOIN LettingUnits lu
ON lu.ID = Slots.F_LU_ID
WHERE
Slots.AvailableDays >= #WindowSize
AND (
( DATEDIFF( Slots.EndOfSlot, #EndOfWindow ) >= #WindowSize
AND DATEDIFF( #StartOfWindow, Slots.StartOfSlot ) >= #WindowSize
)
OR
( DATEDIFF( #EndOfWindow, Slots.StartOfSlot ) >= #WindowSize
AND DATEDIFF( Slots.EndOfSlot, #StartOfWindow ) >= #WindowSize
)
)
Gives
Name F_LU_ID StartOfSlot EndOfSlot AvailableDays
Foo Cottage 123 2009-01-06 2009-01-09 5
Foo Cottage 123 2009-01-21 2009-01-24 5
Hopefully that can be adapted to suit your needs.
Alternatively, if a booking can start on the same day that the previous booking ends, you can adapt slightly...
SELECT
lu.Name,
Slots.*
FROM (
SELECT
lub1.F_LU_ID,
MAX( lub2.date_time ) AS StartOfSlot,
lub1.date_time AS EndOfSlot,
DATEDIFF( lub1.date_time, MAX( lub2.date_time )) AS AvailableDays
FROM
( SELECT F_LU_ID, Start AS date_time FROM LettingUnitBookings
UNION
SELECT F_LU_ID, CAST( '9999-12-31' AS DATE ) FROM LettingUnitBookings
) AS lub1,
( SELECT F_LU_ID, End AS date_time FROM LettingUnitBookings
UNION
SELECT F_LU_ID, CAST( '1000-01-01' AS DATE ) FROM LettingUnitBookings
) AS lub2
WHERE
lub2.date_time <= lub1.date_time
AND lub2.F_LU_ID = lub1.F_LU_ID
GROUP BY
lub1.F_LU_ID,
lub1.date_time
) Slots
JOIN LettingUnits lu
ON lu.ID = Slots.F_LU_ID
WHERE
Slots.AvailableDays >= #WindowSize
AND
( DATEDIFF( Slots.EndOfSlot, #EndOfWindow ) >= #WindowSize
AND DATEDIFF( #StartOfWindow, Slots.StartOfSlot ) >= #WindowSize
)
OR
( DATEDIFF( #EndOfWindow, Slots.StartOfSlot ) >= #WindowSize
AND DATEDIFF( Slots.EndOfSlot, #StartOfWindow ) >= #WindowSize
)

Related

Calculating Time Difference Between Current Row and Previous Row

I have following table for my web application and i want add another column to get time difference between current row and previous row. How can i achieve it?
Currently here is my sql call from php Application
$stmt = $db->prepare("SELECT device,lat,lon, speed, mode, DATE (`currentTime`) ,TIME_FORMAT(`currentTime`, '%H:%i:%s')
FROM myTable
WHERE device=? limit ?");
$stmt ->bind_param('ii', $device_Number ,$limit);
$stmt ->bind_result($device, $lat, $lon, $speed, $mode, $currentDate, $currentTime);
$stmt ->execute();
Here I give sample datas with datetime difference, here you are saving the data in 2 different column
so take date difference as 2 column 'timedifference' and 'daydifference'
testtime table
id date1 time1
1 2017-08-14 01:06:11
2 2017-08-14 01:09:13
3 2017-08-14 01:16:10
4 2017-08-14 01:21:00
5 2017-08-15 01:21:00
6 2017-08-15 02:13:00
Mysql Query is
SELECT A.id, A.time1, TIMESTAMPDIFF(SECOND,A.time1,B.time1) AS timedifference,
TIMESTAMPDIFF(DAY,A.date1,B.date1) AS daydifference
FROM testtime A INNER JOIN testtime B ON B.id = (A.id + 1)
ORDER BY A.id ASC
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(device INT NOT NULL
,lat DECIMAL(10,6) NOT NULL
,lon DECIMAL(10,6) NOT NULL
,speed DECIMAL(5,2)
,mode INT NOT NULL
,dt DATETIME NOT NULL
,PRIMARY KEY(device,dt)
);
INSERT INTO my_table VALUES
(117,1.415738,103.82360,28.8,3,'2017-07-12 22:07:40'),
(117,1.424894,103.82561,31.9,3,'2017-07-12 22:08:41'),
(117,1.429965,103.82674,10.9,3,'2017-07-12 22:09:47'),
(117,1.430308,103.82873, 5.2,3,'2017-07-12 22:10:47'),
(117,1.430542,103.83278,13.9,3,'2017-07-12 22:11:48'),
(117,1.430537,103.83325, 3.2,3,'2017-07-12 22:12:47');
SELECT x.*
, SEC_TO_TIME(TIME_TO_SEC(x.dt)-TIME_TO_SEC(MAX(y.dt))) diff
FROM my_table x
LEFT
JOIN my_table y
ON y.device = x.device
AND y.dt < x.dt
GROUP
BY x.device
, x.dt;
+--------+----------+------------+-------+------+---------------------+----------+
| device | lat | lon | speed | mode | dt | diff |
+--------+----------+------------+-------+------+---------------------+----------+
| 117 | 1.415738 | 103.823600 | 28.80 | 3 | 2017-07-12 22:07:40 | NULL |
| 117 | 1.424894 | 103.825610 | 31.90 | 3 | 2017-07-12 22:08:41 | 00:01:01 |
| 117 | 1.429965 | 103.826740 | 10.90 | 3 | 2017-07-12 22:09:47 | 00:01:06 |
| 117 | 1.430308 | 103.828730 | 5.20 | 3 | 2017-07-12 22:10:47 | 00:01:00 |
| 117 | 1.430542 | 103.832780 | 13.90 | 3 | 2017-07-12 22:11:48 | 00:01:01 |
| 117 | 1.430537 | 103.833250 | 3.20 | 3 | 2017-07-12 22:12:47 | 00:00:59 |
+--------+----------+------------+-------+------+---------------------+----------+
6 rows in set (0.00 sec)

How to select calls, answers, deals, rate and etc. by working time?

I need to select calls, answers, deals, rate, talking_time by the grouped working time.
Here is my select:
SELECT
users.username as username,
DATE_FORMAT(users_worktime.start,'%Y-%m-%d') as start,
SUM(users_worktime.length) as working_time
FROM
users_worktime
LEFT JOIN users ON users.id = users_worktime.user_id
WHERE 1
AND users_worktime.user_id = '8'
AND users_worktime.start >= '2015-12-30 00:00:00'
AND users_worktime.start <= '2015-12-31 23:59:59'
GROUP BY
DAY(users_worktime.start)
It's all good, i got 2 rows by date 2015-12-30 and 2015-12-31:
| username | start | working_time |
-----------------------------------------
| Haroldas | 2015-12-30 | 85.00 |
| Haroldas | 2015-12-31 | 170.00 |
And my question: how to select COUNT calls from table calls, answers - SUM all calls where status = 'ended', select COUNT deals from table orders, rate - Deals / SUM calls, and talking_time - calls.call_length. And all of these select by the grouped working time.
I need result like this:
| username | start | calls | answers | deals | rate | talking_time| working_time |
----------------------------------------------------------------------------------------
| Haroldas | 2015-12-30 | 1 | 1 | 1 | 100% | 35 | 85.00 |
| Haroldas | 2015-12-31 | 3 | 2 | 1 | 50% | 160 | 170.00 |
And here are my data tables:
users_worktime:
| id | user_id | length | start |
-----------------------------------------------
| 1 | 8 | 30 | 2015-12-30 07:53:38 |
| 2 | 8 | 55 | 2015-12-30 12:53:38 |
| 3 | 8 | 170 | 2015-12-31 22:53:38 |
users:
| id | username |
-----------------
| 8 | Haroldas |
calls:
| id | user_id | order_id | status | call_length | created_at |
-------------------------------------------------------------------------
| 1 | 8 | 3 | ended | 35 | 2015-12-30 07:53:38 |
| 2 | 8 | 4 | ended | 100 | 2015-12-31 12:53:38 |
| 3 | 8 | NULL | started | 15 | 2015-12-31 14:53:38 |
| 4 | 8 | NULL | ended | 45 | 2015-12-31 20:53:38 |
orders:
| id | user_id | call_id | start |
-----------------------------------------------
| 3 | 8 |1 | 2015-12-30 07:53:38 |
| 4 | 8 |2 | 2015-12-31 12:53:38 |
How many calls / answers / deals / etc / were when user Haroldas working on these days.
Thank you
You could use subqueries to achive your goal. I've also changed your base query because you'll not see records if user didn't work at specified period of time.
SELECT T2.*,
(deals / answers_cnt) * 100 AS rate
FROM
(SELECT T.username,
T.day_start
SUM(T.working_time) AS working_time,
(SELECT COUNT(*) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id) AS calls_cnt,
(SELECT COUNT(*) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id
AND C.status = 'ended') AS answers_cnt,
(SELECT SUM(call_length) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id) AS talking_time,
(SELECT COUNT(*) FROM orders AS O
WHERE DATE(O.start) = T.day_start
AND O.user_id = T.user_id) AS deals_cnt
FROM
(SELECT U.username,
U.id AS user_id,
DATE(UW.start) as day_start,
UW.length AS working_time
FROM users AS U
LEFT JOIN users_worktime AS UW ON UW.user_id = U.id
WHERE U.id = 8
AND UW.start >= '2015-12-30 00:00:00'
AND UW.start <= '2015-12-31 23:59:59') AS T
GROUP BY T.username, T.user_id, T.day_start
) AS T2
You can LEFT JOIN by user_id plus DAY of time. E.g.
FROM
users_worktime
LEFT JOIN users ON users.id = users_worktime.user_id
LEFT JOIN users ON users.id = calls.user_id
AND DAY(users_worktime.start)=DAY(calls.created_at)
Then apply all necessary aggregate functions to the calls data

force count to be zero in a mysql query

I have two tables t1, t2 and the following query:
SELECT t2.year,
Count(t1.id) AS count
FROM t1,
t2
WHERE t2.t1id = t1.id
AND t2.year IN ( 1995, 1996, 1997, 1998,
1999, 2000 )
GROUP BY t2.year
ORDER BY t1.year
Which results in:
+----------+--------+
| year | count |
+----------+--------+
| 1995 | 1 |
| 1998 | 3 |
| 1999 | 3 |
| 2000 | 28 |
+----------+--------+
And as you can see some years are missing. Is it possible to rewrite this query such that it results in?
+----------+--------+
| year | count |
+----------+--------+
| 1995 | 1 |
| 1996 | 0 |
| 1997 | 0 |
| 1998 | 3 |
| 1999 | 3 |
| 2000 | 28 |
+----------+--------+
I could use php and check which rows are missing to fill in the missing gaps, but that doesn't seem very efficient.. Any ideas?
edit
t1
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(128) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
t2
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| t1id | int(11) | NO | | NULL | |
| year | int(11) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
For example:
t1
+----------+---------+
| id | name |
+----------+---------+
| 1 | john |
| 2 | bob |
| .. | .. |
+----------+---------+
t2
+----------+---------+---------+
| id | t1id | year |
+----------+---------+---------+
| 100 | 1 | 1995 |
| 101 | 2 | 1998 |
| 103 | 3 | 1998 |
| .. | .. | .. |
+----------+---------+---------+
Where after the combination I end up with:
+----------+---------+
| id | year |
+----------+---------+
| 100 | 1995 |
| 101 | 1998 |
| 103 | 1998 |
| .. | .. |
+----------+---------+
SELECT t2.year,
IF(Count(t1.id) > 0, Count(t1.id), 0)
FROM t1,
t2
WHERE t2.t1id = t1.id
AND t2.year IN ( 1995, 1996, 1997, 1998,
1999, 2000 )
GROUP BY t2.year
ORDER BY t1.year
Without a source of all possible years that your query could cover you are going to have to use php to do this. One approach would could look something like this.
function getCountsForRange(\PDO $dbConn, $startYear, $endYear){
$ret = array_fill_keys(range($startYear, $endYear), 0);
$stmt = $dbConn->prepare("SELECT t2.year,Count(t1.id) AS count ".
"FROM t1,t2 ".
"WHERE t2.t1id = t1.id AND t2.year between ? and ? ".
"GROUP BY t2.year ORDER BY t1.year");
$stmt->execute([$startYear, $endYear]);
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
$ret[$row["year"]] = $row["count"];
}
return $ret;
}
create table yrCheat
( year int not null
);
create table t1
( -- forgive lack of PK
id int not null,
name varchar(128) not null
);
create table t2
( -- forgive lack of PK
id int not null,
t1id int not null,
year int not null
);
insert t1(id,name) values (100,'john'),(101,'bob'),(102,'sally');
insert t2(id,t1id,year) values (100,1,1995),(101,2,1998),(101,3,1998),(101,4,1998);
insert into yrCheat (year) values (1990),(1991),(1992),(1993),(1994),(1995),(1996),(1997),(1998),(1999),(2000);
-- etc
select yc.year,count(t1.id) as count
from yrCheat yc
left join t2
on t2.year=yc.year -- and yc.year in (1995,1996,1997,1998,1999,2000)
left join t1
on t1.id=t2.id
where yc.year in (1995,1996,1997,1998,1999,2000)
group by yc.year
order by yc.year
+------+-------+
| year | count |
+------+-------+
| 1995 | 1 |
| 1996 | 0 |
| 1997 | 0 |
| 1998 | 3 |
| 1999 | 0 |
| 2000 | 0 |
+------+-------+
6 rows in set (0.00 sec)
You will need to handle the empty rows pragmatically or in the query itself depending on the situation.
See:
MySQL GROUP BY and Fill Empty Rows
or
Populating query results with empty rows
For some ideas.

How to combine this two MySQL query using Group By

I have this table that i use to query by grouping via station_id.
+------------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+---------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| station_id | tinyint(3) | NO | | NULL | |
| game_type_id | smallint(1) | NO | MUL | NULL | |
| price | decimal(10,2) | YES | | 0.00 | |
| date_created | datetime | YES | MUL | NULL | |
| bet_no1 | tinyint(2) | YES | | 0 | |
| bet_no2 | tinyint(2) | YES | | 0 | |
+------------------+---------------+------+-----+---------+-------+
Here is the query i use to display it on a table using GROUP BY station_id
SELECT station_id,
COUNT(*) as bet_counts,
FORMAT(SUM(price),2) as gross
FROM bets
WHERE bet_void=0
AND date_created >= '2013-02-12 00:00:00'
AND date_created < '2013-02-23 00:00:00'
GROUP BY station_id
The query will give me.
+------------+------------+-------+
| station_id | bet_counts | gross |
+------------+------------+-------+
| 1 | 14 | 16.00 |
| 2 | 5 | 5.00 |
| 7 | 11 | 11.00 |
+------------+------------+-------+
But i also have another query that counts each specific bets( game_type_id ) from each station_id. I usually query this inside the a looping statement.
SELECT COUNT(*) as count
FROM bets
WHERE game_type_id = 1
AND station_id = {station_id from first query}
AND date_created >= '2013-02-12 00:00:00'
AND date_created < '2013-02-23 00:00:00'
My question is, how can i make this in one query and still use the GROUP BY station_id and also get the count of bets on each game_type_id? Something like this result.
+------------+------------+-------+-------------------------+-------------------------+
| station_id | bet_counts | gross | count_of_game_type_id_1 | count_of_game_type_id_2 |
+------------+------------+-------+-------------------------+-------------------------+
| 1 | 14 | 16.00 | 10 | 4 |
| 2 | 5 | 5.00 | 3 | 2 |
| 7 | 11 | 11.00 | 11 | 0 |
+------------+------------+-------+-------------------------+-------------------------+
You can do this by joining the results together. However, the logic in the two queries is very similar, so you can combine them into a single aggregation query:
SELECT station_id,sum(case when bet_void = 0 then 1 else 0 end) as bet_counts,
FORMAT(SUM(case when bet_void = 0 then price else 0 end),2) as gross,
sum(case when game_type_id = 1 then 1 else 0 end) as count
FROM bets b
where date_created >= '2013-02-12 00:00:00' AND date_created < '2013-02-23 00:00:00'
GROUP BY station_id

SQL query help request

user table
.--------------------------------.
| userid| val | Create_Date |
.--------------------------------.
| U1 | foo | 2011-05-01 |
| U1 | foo | 2011-11-18 |
| | | |
| U2 | foo | 2011-11-18 |
| U2 | foo | 2011-11-28 |
| | | |
| U3 | foo | 2011-04-11 |
| U3 | foo | 2011-11-04 |
| | | |
| U4 | foo | 2011-11-21 |
| U4 | foo | 2011-11-28 |
.________________________________.
I have a table similar to the above one. What I need to get is the latest record, and make sure that the latest record is more than 5 days the current date.
for instance, the current date is 2011-11-29
the output of the SQL statement should be
.--------------------------------.
| userid| val | Create_Date |
.--------------------------------.
| U3 | foo | 2011-11-04 |
| U1 | foo | 2011-11-18 |
.________________________________.
my current SQL is able to get the latest records but unable to compare to the latest date.
please help me debug. thanks.
SELECT * FROM user_table t1
WHERE DATEDIFF(NOW(), (SELECT MAX(create_date)
FROM user_table t2
WHERE t2.userid = t1.userid)) > 5
thanks in advance.
You could use a subquery to filter out older records per user. Then you can use a where condition to demand that the latest record is more than five days old.
select *
from UserTable u
join (
select userid
, max(Create_Date) as LatestCreateDate
from YourTable
group by
userid
) filter
on filter.userid = u.userid
and filter.LatestCreateDate = u.Create_Date
where datediff(now(), u.Create_Date) > 5
Try:
select user_id, val, min(Create_date)
from table
group by user_id
having datediff(now(), min(Create_date)) > 5

Categories