Having子句跳过计算字段的值

时间:2016-03-27 21:00:25

标签: mysql sql mariadb

场景:每个用户每天只处理100个项目的项目队列。

说明:以下是过去24小时处理过的记录与未处理项目的自我联接,其中包含剩余的每日配额。

SELECT 
    q.*, 
    case when delivery.processed is null then 0 else delivery.processed end as processed, 
    @subcounter := IF(@context = q.user_id, @subcounter+1, 1) as counter,
    @context := q.user_id as uid 
from queue q

LEFT JOIN (
    SELECT `user_id`, count(*) as `processed` FROM `queue` 
    where `status` = 'processed' and `updated_at` >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    GROUP BY `user_id`) as `delivery`
    ON `delivery`.`user_id` = `q`.`user_id`

WHERE 
    `q`.`status` = 'queued' and 
    (`delivery`.`processed` is null or `delivery`.`processed` < 100)
HAVING
    `counter` <= (100 - `delivery`.`processed`)

最终条件counter <= (100 - delivery.processed)错误地跳过计数器为偶数的每个备用行。

如果没有这个最终条件,我就不能跳过那些超过每日配额限制100的记录。

Table: queue
Columns:
id  bigint(20) UN AI PK
created_at  timestamp
updated_at  timestamp
job_id  bigint(20)
user_id bigint(20)
status  varchar(64)

以下是查询结果:(第二列最后一列缺失序列,由于条款条件而跳过所有均值数字)

'224244', '2016-03-24 22:44:32', '2016-03-24 22:44:32', '23942', '3', 'queued', '0', '1', '3'
'224995', '2016-03-24 22:45:25', '2016-03-24 22:45:25', '23963', '3', 'queued', '0', '3', '3'
'225208', '2016-03-24 22:45:40', '2016-03-24 22:45:40', '23970', '3', 'queued', '0', '5', '3'
'225316', '2016-03-24 22:45:47', '2016-03-24 22:45:47', '23972', '3', 'queued', '0', '7', '3'
'227247', '2016-03-27 15:17:00', '2016-03-27 15:17:00', '22741', '3', 'queued', '0', '9', '3'
'227258', '2016-03-27 15:17:00', '2016-03-27 15:17:00', '22747', '3', 'queued', '0', '11', '3'
'228291', '2016-03-27 15:18:22', '2016-03-27 15:18:22', '24537', '3', 'queued', '0', '13', '3'

1 个答案:

答案 0 :(得分:0)

我认为你需要一个额外的图层 - 并且你需要额外的SELECT。除了,移动最外面的HAVING,此时您可以将其更改为WHERE