组合从多个表中选择,每组最大值

时间:2014-03-26 17:45:41

标签: mysql

我正在尝试几天来解决以下问题:让我们说我们有

表用户

user_id, credit

表格属性

property_id, user_id, check_interval

表states_(年)(即多个表 - 每年一个,从2010年开始 - 即states_2010 - 申请出生时)

property_id, timestamp

背后的逻辑是每个用户都有一个或多个属性。每个属性都有一个或多个状态。从时间戳开始获取每个州。每个特定时间获取一次状态,即check_interval(针对每个特定属性)。获取每个州为每个用户收取一笔从用户帐户中扣除的信用(表用户)。

我的目标是从计划在不久的将来开始的检查中获得property_ids和下次检查时间(每个property_id只有一次)的概述。下次检查的时间是最后一个状态的时间戳(即来自所有states_(年)表的max(时间戳))加上check_interval。该概述应仅包含属于具有一定功劳的用户的属性的property_id(即信用> 0)。

我发现了一个非常接近的问题(Get max row per group from a related table),但它只涉及三个表,并且只是部分地解决了我的问题。就我而言,用户信用和多个州_(年)表也很复杂,这是我无法打破的。

1 个答案:

答案 0 :(得分:0)

您可能希望首先尝试使用视图来克服state_ [year]难度。

CREATE VIEW super_states AS
SELECT property_id, `timestamp` FROM states_2013
UNION
SELECT property_id, `timestamp` FROM states_2012
UNION
SELECT property_id, `timestamp` FROM states_2011;

{根据需要继续}

然后尝试这个SQL

SELECT properties.property_id
  , DATE_ADD(states.most_recent, properties.check_interval SECONDS) AS Next_Time
FROM properties
JOIN users
  ON properties.user_id = users.user_id
LEFT JOIN (SELECT property_id, MAX(timestamp) AS most_recent
           FROM super_states
           GROUP BY property_id) AS states
  ON states.property_id = properties.property_id
WHERE users.credit > 0;

编辑 - 反馈后

步骤1.检查视图 - 这看起来不错吗?

SELECT * FROM super_states LIMIT 20;

步骤2.检查显示每个属性的最新时间戳的子查询

SELECT property_id, MAX(`timestamp`) AS most_recent
FROM super_states
GROUP BY property_id;

步骤3.尝试解决方案的此变体

SELECT properties.property_id
  , states.most_recent AS most_recent
  , properties.check_interval AS seconds_to_next_check
  , DATE_ADD(states.most_recent, properties.check_interval SECONDS) AS Next_Time
FROM properties
JOIN users
  ON properties.user_id = users.user_id
LEFT JOIN (SELECT property_id, MAX(`timestamp`) AS most_recent
           FROM super_states
           GROUP BY property_id) AS states
  ON states.property_id = properties.property_id
WHERE users.credit > 0;