我试图获得用户拥有的积分总数,以及当前月份积分.当用户获得一个点时,它会使用时间戳记录到点表中.总计会忽略时间戳,而当前月份的点会查找具有正确时间戳的点(从该月的第一天开始).
SELECT user_id, user_name, sum(tpoints.point_points) as total_points, sum(mpoints.point_points) as month_points FROM users LEFT JOIN points tpoints ON users.user_id = tpoints.point_userid LEFT JOIN points mpoints ON (users.user_id = mpoints.point_userid AND mpoints.point_date > '$this_month') WHERE user_id = 1 GROUP BY user_id
点表结构
CREATE TABLE IF NOT EXISTS `points` ( `point_userid` int(11) NOT NULL, `point_points` int(11) NOT NULL, `point_date` int(11) NOT NULL, KEY `point_userid` (`point_userid`), KEY `point_date` (`point_date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
这导致非常大的数量,即等于所有点的总和,乘以与查询匹配的行数.
我需要在不使用子查询或多个查询的情况下实现此目的.
尝试
SELECT user_id, user_name, sum(point_points) as total_points, sum( case when point_date > '$this_month' then point_points else 0 end ) as month_points FROM users LEFT JOIN points ON users.user_id = points.point_userid WHERE user_id = 1 GROUP BY user_id, user_name