I have a question in which I need to know the number of updates since the last time a user enters a thread .
Each time a user enters a thread, the following query is executed:
INSERT INTO visita_post ('postId', 'nick', 'fecha_ultimo_acceso')
VALUES(?, ?, sysdate())
ON DUPLICATE KEY UPDATE fecha_ultimo_acceso = sysdate()'
And it is added to the table visita_post
that has the following structure:
postId int(11)
nick varchar(30)
fecha_ultimo_acceso datatime
To see how many updates have been made since the last visit, I run the following query:
SELECT
p.count(id) nActualizacion,p.hiloid,
p.post_tema
from post p, visita_post v
where p.post_tema = v.postId
and p.fecha > v.fecha_ultimo_acceso
and v.nick = ?
and p.hiloid = ?
group by p.hiloid,
p.post_tema
The query shows me how many new posts there have been since the last time the insert
was executed but this query has several problems that I can not solve.
- If you have never entered a thread it does not show any updates but I need to show all the updates. This part is a bit confusing written in this way, so I will try to explain it with examples.
If you execute the second query without using the visita_post
table with this query:
SELECT count(id) nActualizacion,
post_tema,hiloid
from post
where
hiloid is not null
GROUP By post_tema,hiloid
I get the result in nActualizacion
the total number of updates that exist. I would like that in case the user has never executed the first query the data of this one will be shown.
- If there are no updates, I need you to return 0, instead of no rows.
EDITION
Right now I have the following query:
SELECT COUNT(DISTINCT
CASE
WHEN p.fecha > v.fecha_ultimo_acceso THEN v.postID
WHEN v.postId IS NULL THEN p.id
END) nActualizacion,
p.hiloid,
p.post_tema,
v.fecha_ultimo_acceso
FROM post p
LEFT JOIN ( SELECT *
FROM visita_post
WHERE nick = "testing") v
ON p.post_tema = v.postId
AND p.fecha > v.fecha_ultimo_acceso
WHERE p.hiloid = 27
and p.post_tema is not null
GROUP BY p.hiloid,
p.post_tema
If I execute it like this right now it does not count the results well, but executing it in the same way adding a and p.fecha > v.fecha_ultimo_acceso
in the line before group by shows me the result correctly but it does not show me the rows that do not exist in the table visita_post
.
If you need more information about the database, ask for it in the comments and attach it