我的MYSQL查询中有一个小的语法问题我似乎无法修复,看起来相当简单,这里是查询:
$dates = DB::getInstance()->select("
SELECT today.clicks AS clicksToday, today.spend_amount AS amountToday,
yesterday.clicks AS clicksYesterday, yesterday.spend_amount AS amountYesterday,
week.clicks AS clicksWeekly, week.spend_amount AS amountWeekly,
month.clicks AS clicksMonthly, month.spend_amount AS amountMonthly
FROM
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE()) today
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 1 DAY
AND spend_date < CURDATE()) yesterday
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 7 DAY
AND spend_date < CURDATE()) week
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH) month
JOIN WHERE spend_user_id='{$globId}'";
问题在于这一部分: JOIN WHERE spend_user_id ='{$ globId}''; $ globId包含用户唯一ID,如果我走这条线它可以正常工作但是拉出所有数据,我真的需要它使用ID,我不能确切地看到我做错了什么,任何帮助将不胜感激。
SQLFiddle: http://sqlfiddle.com/#!9/c3c694/1
答案 0 :(得分:0)
我会将spend_user_id
过滤器合并到子查询中:
$dates = DB::getInstance()->select("
SELECT today.clicks AS clicksToday, today.spend_amount AS amountToday,
yesterday.clicks AS clicksYesterday, yesterday.spend_amount AS amountYesterday,
week.clicks AS clicksWeekly, week.spend_amount AS amountWeekly,
month.clicks AS clicksMonthly, month.spend_amount AS amountMonthly
FROM
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() AND spend_user_id='{$globId}') today
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 1 DAY
AND spend_date < CURDATE() AND spend_user_id='{$globId}') yesterday
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 7 DAY
AND spend_date < CURDATE() AND spend_user_id='{$globId}') week
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH AND spend_user_id='{$globId}') month";