2

我有两个表,“问题”:问题列表,“QResults”用户对这些问题的结果。在再次询问之前,这些问题会在几小时内超时。

Table: Questions
   ID
   Timeout - The amount of time before asking the question again 

Table: Results
   ID 
   Created (timestamp) - When this record was added. 
   Questions_ID - A FK to the Question table 

示例数据

Table: Questions
 ID | Timeout (hrs) 
--------------
  1 | 1    
  8 | 6 
 15 | 1 
 55 | 1

Table: QResults
ID | Created            | Q_ID 
-------------------------------
 1 | Jan 24, 2012 00:00 |    1 
 2 | Jan 24, 2012 06:05 |   15 
 3 | Jan 24, 2012 02:00 |    8 
 4 | Jan 24, 2012 01:00 |    1 
 5 | Jan 24, 2012 02:00 |    1 

我正在寻找的是一个查询,它将根据上次回答问题的时间 + 超时对问题进行排序。如果问题从未得到回答,则应将其推到列表顶部。

例如,如果查询是在上述数据上运行的,它将产生以下数据集。

The result of the query I am looking for. 
ID | timeout + created aka eligible
-------------------------------
55 | Jan 01, 1970 01:00 *(1) See note below*
 1 | Jan 24, 2012 03:00 *(2) See note below* 
 8 | Jan 24, 2012 07:05
15 | Jan 24, 2012 08:00

*注意:(1) id=55 的日期无关紧要,只要它首先出现即可。因为目前没有它的 QResults。(2) 这具有 3hr 的值,因为它使用最新的答案创建时间 + 超时。

让我换一种说法。我正在寻找一个值最低的问题(最后一次询问+超时)。如果问题已被回答 3 次,则应使用最新的问题回答时间 + 超时作为合格值。我希望这是有道理的。

4

2 回答 2

1

像这样的东西,但我会留给你优化:

(select q.id as id, date_add(r.created, interval q.timeout hour) as eligible
from questions q, qresults r
where q.id = r.id)
union (
select q.id as id, '1970-01-01 00:00:00' as eligible
from questions q
where q.id not in
    (select id from qresults r)
)
order by 2 asc
于 2012-07-25T07:01:53.723 回答
1

我现在无法检查语法,但我会做这样的事情。

  • 获取问题表中每个 ID 的最低记录
  • 将结果表中的所有记录以及问题表中的超时附加到这些记录
  • 通过 ID 获取结果的最大值

语法类似于...

更新的语法

select ID, MAX(Timeout) as Timeout
from
(
  (
  select ID, cast('1970-01-01 01:00' as DATETIME) as Timeout
  from Questions
  ) 
union all
  (
  select q.ID, r.created + INTERVAL q.Timeout hour as Timeout
  from QResults as r, Questions as q
  where r.q_ID=q.ID
  ) 
) c
group by ID
order by MAX(Timeout) asc

这给了我以下结果。(请注意与您的订购差异。我认为这就是您的意思。)

ID  Timeout
55  1970-01-01 01:00:00
1   2012-01-24 03:00:00
15  2012-01-24 07:05:00
8   2012-01-24 08:00:00

如果这运行缓慢,您可能希望在连接到问题表以添加超时之前通过 Qresults 表上的 id 获取最大日期。除非您需要,否则我不会打扰这样做,因为它会使查询复杂化,并且 mysql 优化器可能足够聪明,可以自行解决。

于 2012-07-25T07:16:39.673 回答