需要为mysql中的每个类别提取最旧的活动行


Need to pull the oldest active row for each category in mysql

我想知道除了6个单独的选择查询之外,是否还有更好的方法来提取我需要的数据集。

我有一个名为"events"的表,其中包含一个时间戳(日期)、"active"列(int 1是活动的)、一个"category"列(有6个类别,这是int)和一个"ispaid"列(int 1是付费的)的事件。我需要按每个类别提取最古老的活动付费活动。我已经处理了6个不同的选择查询,但我担心随着数据库越来越大,这可能会降低效率。

我想知道是否有更好的方法?

Events Table
------------
id       INT
ispaid   INT  -- 1 is paid
category INT  -- references another table but dont need to join as of now
active   INT  -- 1 is active
ts       DATE -- event date

类似的东西?

SELECT *
FROM events_tbl
WHERE events_tbl.active = 1 AND events_tbl.ispaid = 1
GROUP BY events_tbl.category
ORDER BY events_tbl.ts ASC

如果我没有弄错,很可能你正在寻找这样的东西:

select e1.* from events e1
join (
  select category, min(ts) oldestDate from events
  where ispaid = 1 and active = 1
  group by category
) e2 on e1.category = e2.category and e1.ts = e2.oldestDate
where e1.ispaid = 1 and e1.active = 1

这将为每个类别获得已付款且处于活动状态的最早日期。然后,这些数据被连接回事件表。双where子句应该比只留下外部子句更快,因为在内部select中处理的记录更少。