在SELECT中设置一个带有2个元素的var

时间:2012-08-03 03:32:33

标签: mysql sql triggers

我只想将COUNT(page_ID)值作为@current_rank,但我被迫更多地使用MAX(rating_time),因为我可以有几个关于WHERE子句的“page_ID”记录但是在不同的日期(“rating_time” “)。

在这些潜在的多个page_ID记录中,我想要最新的。

SET @current_rank = (SELECT COUNT(page_ID), MAX(rating_time)
    FROM ranks_update
    WHERE ranking_ID = NEW.ranking_ID
        AND page_ID <> NEW.page_ID 
        AND current_sum_vote >= @current_sum_vote
        AND rating_time >= ( *** a subquery *** ) 
    GROUP BY page_ID);

PS:我在MySQL中使用触发器。

3 个答案:

答案 0 :(得分:1)

SELECT @current_rank = COUNT(page_ID), @max_rating = MAX(rating_time)
    FROM ranks_update
    WHERE ranking_ID = NEW.ranking_ID
        AND page_ID <> NEW.page_ID 
        AND current_sum_vote >= @current_sum_vote
    GROUP BY page_ID;

答案 1 :(得分:0)

如果具有MAX函数的目的是过滤记录,则宁可在子查询中放入where子句。如下所示:

SET @current_rank = (SELECT COUNT(page_ID)
FROM ranks_update
WHERE ranking_ID = NEW.ranking_ID
    AND page_ID <> NEW.page_ID 
    AND current_sum_vote >= @current_sum_vote
    AND rating_time in 
    (select MAX(rating_time) from ranks_update as ru where ru.page_ID = NEW.page_ID)
GROUP BY page_ID);

答案 2 :(得分:0)

我认为解决方案是(如果我错了请纠正我):

SELECT COUNT(page_ID)
    FROM (
    SELECT page_ID, MAX(rating_time)
    FROM ranks_update
    WHERE ranking_ID = NEW.ranking_ID
        AND page_ID <> NEW.page_ID 
        AND current_sum_vote >= @current_sum_vote
        AND rating_time >= (*** a subquery ***) 
    GROUP BY page_ID
    ) ru