我有这个查询可以按预期工作,但似乎应该有更好的方法来实现我想要的:
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
表包含start
和end
列,其中包含成员资格有效的日期。我只想查看最后结束的成员资格期间,因此查询子查询中的MAX()
和GROUP BY
。
答案 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)