我有一个查询从数据库表中选择3个随机项,但我需要根据查询中字段的值对查询应用更多逻辑。
这是我迄今为止希望它有意义的东西。还没有完全测试它,但我发现我会通过你们先看看是否有任何跳出来。
SELECT ord.id, keyword, url, daily_max
FROM orders AS ord
LEFT JOIN product_tasks AS tsk ON tsk.id = ord.task_id
LEFT JOIN product_groups AS grp ON grp.id = tsk.product_group
WHERE (
status = 'approved' AND
ord.total_actions_today < tsk.daily_max AND
grp.id = 1 AND
country_code = '$country' AND
(
CASE WHEN daily_max >= 5 THEN last_displayed < (NOW() - INTERVAL 30 MINUTE)
CASE WHEN daily_max >10 THEN last_displayed < (NOW() - INTERAVAL 5 MINUTE)
ELSE last_displayed < (NOW() - INTERAVAL 60 MINUTE)
)
)
GROUP BY ord.id
ORDER BY RAND()
LIMIT 3
刚刚测试了查询,因为我怀疑我的语法有误,所以任何帮助都会受到赞赏:
#1064 - 您的SQL语法出错;检查与您的MySQL服务器版本对应的手册,以便在'CASE WHEN daily_max&gt;附近使用正确的语法10然后last_displayed&lt; (现在() - 行间5分钟)'第14行
编辑 - 修正
(经过多次尝试+编辑):
SELECT ord.id, keyword, url, daily_max
FROM orders AS ord
LEFT JOIN product_tasks AS tsk ON tsk.id = ord.task_id
LEFT JOIN product_groups AS grp ON grp.id = tsk.product_group
WHERE (
status = 'approved' AND
ord.total_actions_today < tsk.daily_max AND
grp.id = 1 AND
country_code = 'us'
AND last_displayed <
CASE WHEN (daily_max >= 5) THEN (NOW() - INTERVAL 30 MINUTE)
WHEN (daily_max >10) THEN (NOW() - INTERVAL 5 MINUTE)
ELSE (NOW() - INTERVAL 60 MINUTE)
END
)
GROUP BY ord.id
ORDER BY RAND()
LIMIT 3
http://sqlfiddle.com/#!2/ac4499/1
在where语句中解决了DOH )
答案 0 :(得分:1)
您的WHERE结构不正确。请尝试以下方法:
SELECT ord.id, keyword, url, daily_max
FROM orders AS ord
LEFT JOIN product_tasks AS tsk ON tsk.id = ord.task_id
LEFT JOIN product_groups AS grp ON grp.id = tsk.product_group
WHERE (
status = 'approved' AND
ord.total_actions_today < tsk.daily_max AND
grp.id = 1 AND
country_code = '$country' AND
(
CASE WHEN daily_max >10 THEN (NOW() - INTERAVAL 5 MINUTE)
WHEN daily_max >= 5 THEN (NOW() - INTERVAL 30 MINUTE)
ELSE (NOW() - INTERAVAL 60 MINUTE)
END > last_displayed
)
)
GROUP BY ord.id
ORDER BY RAND()
LIMIT 3
答案 1 :(得分:1)
将last_displayed移出CASE,以便将其与CASE语句中预测的单个值进行比较:
WHERE...
AND last_displayed <
CASE WHEN (daily_max >= 5) THEN (NOW() - INTERVAL 30 MINUTE)
WHEN (daily_max >10) THEN (NOW() - INTERVAL 5 MINUTE)
ELSE (NOW() - INTERVAL 60 MINUTE)
END;
另请注意一些拼写错误 - INTERVAL
而不是INTERAVAL
,只需要一个CASE
。