2

I'm trying to write a query to find an eligble key. The criteria for an key being eligble is that it must not have been used 10 times within 24 hrs.

Every time a key has been used, a record is saved in my table api_history.

Can anyone please teach me how to do it correctly? Currently I'm getting an empty key returned, as no records exists in the api_history. (Then it should just have returned the first giving key).

Thanks in advance!

Query:

SELECT ak.key 
FROM api_history ah 
  INNER JOIN api_keys ak ON ah.key_id = ah.id 
WHERE ah.used_at > DATE_SUB(now(), INTERVAL 1 DAY) 
HAVING COUNT(ah.id) < 10 LIMIT 0,1

Tables:

api_keys

  • id (int)
  • key (string)

api_history

  • id (int)
  • key_id (int)
  • used_at (datetime)
4

3 回答 3

2

它对你有用吗?

SELECT ak.key, COUNT(ah.id) as num_usage_24hrs 
FROM api_keys  ak
LEFT JOIN api_history ah ON (ah.key_id = ak.id 
    AND ah.used_at > DATE_SUB(now(), INTERVAL 1 DAY) )    
GROUP BY ak.key
HAVING COUNT(ah.id) < 10 

** 你可能不需要COUNT(ah.id) as num_usage_24hrsin select,我输出它只是为了调试。

更新 (应该是ah.key_id = ak.id,不是ah.key_id = ah.id

于 2012-08-03T14:11:01.017 回答
2

试试看:

SELECT ak.key 
FROM api_keys ak
  LEFT JOIN api_history ah 
    ON  ah.key_id = ak.id 
    AND ah.used_at > DATE_SUB(now(), INTERVAL 1 DAY)
WHERE 1 
GROUP BY ak.key
HAVING COUNT(ah.id) < 10 
LIMIT 1
于 2012-08-03T14:14:50.703 回答
1

如果我理解正确,我认为您想要 api_keys 表中的最大键。所以也许你可以做这样的事情?

SELECT max(ak.key) 
FROM api_keys ak
WHERE NOT EXISTS
(SELECT * FROM api_history ah 
WHERE ah.key_id = ak.id AND ah.used_at > DATE_SUB(now(), ITERVAL 1 DAY))
GROUP BY ah.key_id
HAVING COUNT(ah.id)<10)
于 2012-08-03T14:32:21.973 回答