替代过滤的子查询

时间:2011-06-09 17:02:13

标签: mysql subquery

我有这个查询可以按预期工作,但似乎应该有更好的方法来实现我想要的:

SELECT `x`.*
FROM (
    SELECT `m`.`id`,
        `m`.`email`,
        MAX(`s`.`end`) AS `max_end`
    FROM `members` AS `m`
    INNER JOIN `memberships` AS `s`
        ON `m`.`id` = `s`.`member_id`
    GROUP BY `m`.`id`,
        `m`.`email`
) AS `x`
WHERE `x`.`max_end` = '2010-02-28 23:59:59'

我正在寻找会员资格在特定日期结束的会员。 memberships表包含startend列,其中包含成员资格有效的日期。我只想查看最后结束的成员资格期间,因此查询子查询中的MAX()GROUP BY

2 个答案:

答案 0 :(得分:2)

可以使用having

重写
SELECT `m`.`id`,
    `m`.`email`
FROM `members` AS `m`
INNER JOIN `memberships` AS `s`
    ON `m`.`id` = `s`.`member_id`
GROUP BY `m`.`id`,
    `m`.`email`
HAVING MAX(`s`.`end`) = '2010-02-28 23:59:59'

答案 1 :(得分:1)

你可以使用一个子查询...在我的脑海中做了多种方式,并以此结算:

select m.* 
from members m
where '2010-02-28 23:59:59' = (select MAX(x.end) 
                               from memberships x 
                               where x.member_id = m.id)

编辑:一种更快捷的方法,将初始群组限制为在该日期拥有会员资格的人。

select m.* 
from members m
join memberships s on m.id = s.member_id
  and s.end = '2010-02-28 23:59:59'
where s.end = (select MAX(x.end) 
               from memberships x 
               where x.member_id = m.id)