返回JOIN查询中的列的SUM

时间:2016-04-05 10:46:31

标签: mysql sql

我有一个包含多个联接的查询,我想从 JOIN评论结果中返回一列的总和...任何想法?

SELECT *,user.id AS u_id
FROM user_connects
    JOIN user ON user_connects.user_y = user.id
    JOIN reviews ON user_connects.user_y = reviews.user
 WHERE user_connects.user_x = 1
 LIMIT 25

我希望返回类似这样的内容,[1]索引 totalcolumls 是评论表的SUM结果:

array(1) {
  [0]=>
  object(stdClass)#26 (12) {
    ["id"]=>
    string(1) "2"
    ["user_x"]=>
    string(1) "1"
    ["user_y"]=>
    string(1) "2"
    ["date_created"]=>
    string(10) "1457593440"
    ["first_name"]=>
    string(6) "Donald"
    ["last_name"]=>
    string(5) "Trump"
    ["age"]=>
    string(2) "68"
    ["gender"]=>
    string(4) "Male"
    ["img_url"]=>
    string(10) "donald.jpg"
    ["keto_score"]=>
    string(1) "5"
    ["date_created_dt"]=>
    string(19) "2016-03-09 07:00:00"
    ["u_id"]=>
    string(1) "2"
  },
  [1]=>
  object(stdClass)#26 (12) {
    ["totalcolumls"]=>
    string(1) "2"
   }
}

1 个答案:

答案 0 :(得分:0)

你可以这样尝试

SELECT count(reviews.*) AS total_review_column, user_connects.*, reviews.*, user.*, user.id AS u_id
FROM user_connects
    JOIN user ON user_connects.user_y = user.id
    JOIN reviews ON user_connects.user_y = reviews.user
 WHERE user_connects.user_x = 1
 group by reviews.user