好的,这里需要一个MySQL大师。我正在尝试编写一个查询,当有人对您之前评论过的项目发表评论时,该查询将作为通知系统。 'drinkComment'表非常简单:
commentID, userID, drinkID, datetime, comment
我写了一个查询,它将获得我之前评论过的所有关于饮料的评论(这不是我的评论),但它仍会显示我评论之前发生的评论。这与我认为可行的一样接近,但事实并非如此。请帮忙!
select @drinkID:=drinkComments.drinkID, commentID, drinkID, userID, comment, datetime
FROM drinkComments
WHERE `drinkID` IN
( select distinct drinkID from drinkComments where drinkComments.userID = 1)
AND drinkComments.dateTime > (
/*This gets the last date user commented on the main query's drinkID*/
select datetime FROM drinkComments WHERE drinkComments.userID = 1 AND drinkComments.drinkID = @drinkID ORDER BY datetime DESC LIMIT 1
)
ORDER BY datetime DESC
答案 0 :(得分:12)
为什么不从用户的预先查询开始,以及他们提供评论的所有饮料以及截止时间(不知道对于任何给定的饮料,您是否每人都有多条评论)。然后,在您的日期/时间评论之后找到所有其他人的评论...
这个查询实际上应该更快,因为它只是以一个用户的饮料评论作为基础开始,然后回到评论表中以查找那些与饮料ID和截止时间相匹配的信息。
SELECT STRAIGHT_JOIN
dc.*
from
( select
drinkID,
max( datetime ) UserID_DrinkCommentTime
FROM
drinkComments
WHERE
userID = 1
group by
drinkID ) PreQuery
join DrinkComments dc
on PreQuery.DrinkID = dc.DrinkID
and dc.datetime > PreQuery.UserID_DrinkCommentTime
order by
dc.DateTime desc
答案 1 :(得分:1)
我认为你需要通过drinkID将最里面的查询与中间查询联系起来。
select @drinkID:=drinkComments.drinkID, commentID, drinkID, userID, comment, datetime
FROM drinkComments
WHERE `drinkID` IN
( select distinct drinkID from drinkComments AS a where drinkComments.userID = 1)
AND drinkComments.dateTime > (
/*This gets the last date user commented on the main query's drinkID*/
select datetime FROM drinkComments WHERE drinkComments.userID = 1 AND drinkComments.drinkID = a.drinkID ORDER BY datetime DESC LIMIT 1
)
ORDER BY datetime DESC