在2个表中查询sum和count

时间:2013-09-18 10:21:31

标签: php mysql

我为我的php脚本使用了2个表。

define("EXTRA_POINTS_VALUE",15);

table "points":
id_user | point
   1    |  500
   2    |  650
   3    |  400

table "points_extra":
id_point_extra | id_user
   1           |   1
   2           |   1
   3           |   1
   4           |   2 

我需要在一个查询中使用COUNT(id_extra_point)* EXTRA_POINTS_VALUE的SUM字段“points.point”。有可能吗?

结果必须如下:

id_user | total_point
   1    |     545     (500 + (3 count * 15))
   2    |     665     (650 + (1 count * 15))
   3    |     400     (400 + (0 count * 15))

1 个答案:

答案 0 :(得分:1)

SELECT  a.id_user,
        a.point + (COUNT(b.id_point_extra) * ?) totalPoints
FROM    points a
        LEFT JOIN points_extra b
            ON a.id_user = b.id_user
GROUP   BY a.id_user
相关问题