I am working on customized shopping cart application.
It have a hits table:
id int
product_id int
hit_time datetime
session_id varchar
Now when someone views a product, I record a hit.
开发者_如何学PythonI need a query such that, record should be inserted only if hit_time has a difference of 30 mins (for same product_id, and session_id)
For example:
When recording first hit
id product_id hit_time session_id
------------------------------------------------------------------------
1 1 2011-01-01 06:30:00 abcxyzmno
2 5 2011-01-01 06:32:00 abcxyzmno
Now, if visitor with same session_id, visit product page with product_id =1 in less than 30 mins, then data should not be inserted
So below row should not be inserted (because there is difference of 5 mins only)
3 1 2011-01-01 06:35:00 abcxyzmno
But if visitor visit after 30 mins, for same product, it should be recorded
3 1 2011-01-01 07:01:15 abcxyzmno
I want single insert query
I DON'T want 2 query, first to select max-time from table, and then insert it
Any help?
Are you looking for something like this?
INSERT INTO hits (product_id, hit_time, session_id)
SELECT $product_id, current_timestamp, $session_id
FROM hits
WHERE NOT EXISTS (
SELECT id
FROM hits
WHERE product_id = $product_id
AND session_id = $session_id
)
OR (
product_id = $product_id
AND session_id = $session_id
AND hit_time < current_timestamp - 30*60
)
LIMIT 1
Where $product_id
and $session_id
are the product and session IDs.
The NOT EXISTS
part takes care of the case where (product_id,session_id) hasn't been recorded yet and the second part takes care of the case where (product_id,session_id) is there but it was longer than 30 minutes ago. And, of course, the LIMIT 1
in case (product_id,session_id) is there and older than 30 minutes ago and appears multiple times.
精彩评论