为什么这个mysql查询给我垃圾结果?

时间:2009-03-04 20:42:28

标签: sql mysql

我试图获得用户拥有的积分总数以及当前月份积分。当用户获得一个点时,它会使用时间戳记录到点表中。总计忽略时间戳,而当前月份的点数会查找具有正确时间戳的点(从该月的第一天开始)。

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;

这导致一个非常大的数字,即等于所有点的总和,乘以与查询匹配的行数。

我需要在不使用子查询或多个查询的情况下实现此目的。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

SELECT user_id, user_name, 
       (
       SELECT  SUM(points.point_points)
       FROM    points
       WHERE   points.point_userid = users.user_id
       ) AS total_points,
       (
       SELECT  SUM(points.point_points)
       FROM    points
       WHERE   points.point_userid = users.user_id
               AND points.point_date > '$this_month'
       ) AS month_points
FROM   users 
WHERE  user_id = 1
相关问题