来自连接的不同表的平均值

时间:2017-07-23 13:50:32

标签: mysql sql

CREATE TABLE `reviews` (
  `id` int(11) NOT NULL,
  `average` decimal(11,2) NOT NULL,
  `house_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `reviews` (`id`, `average`, `house_id`) VALUES
(1, '10.00', 1),
(2, '10.00', 1);
ALTER TABLE `reviews`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `reviews`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

CREATE TABLE `dummy_reviews` (
  `id` int(11) NOT NULL,
  `average` decimal(11,2) NOT NULL,
  `house_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `dummy_reviews` (`id`, `average`, `house_id`) VALUES
(0, '2.00', 1);
ALTER TABLE `dummy_reviews`
  ADD PRIMARY KEY (`id`);

和查询

SELECT
  AVG(r.average) AS avg1,
  AVG(dr.average) AS avg2
FROM
  reviews r
LEFT JOIN
  dummy_reviews dr ON r.house_id = dr.house_id

结果是

avg1        avg2    
10.000000   2.000000

现在好,但是(10 + 2)/ 2 = 6 ......错误的结果

我需要(10 + 10 + 2)/ 3 = 7,33 ......我怎样才能得到这个结果?

SQLFiddle

2 个答案:

答案 0 :(得分:4)

你已经加入了值,因此你不会有3行,你将拥有2.你需要的是一个联合,这样你就可以得到普通表中的所有行并从中进行计算。像这样:

select avg(average) from
  (select average from reviews
   union all
   select average from dummy_reviews
  ) queries

请在此处查看:http://sqlfiddle.com/#!9/e0b75f/3

答案 1 :(得分:3)

Jorge的答案是最简单的方法(我适当地赞成它)。在回复您的评论时,您可以执行以下操作:

select ( (coalesce(r.suma, 0) + coalesce(d.suma, 0)) /
         (coalesce(r.cnt, 0) + coalesce(d.cnt, 0))
       ) as overall_average
from (select sum(average) as suma, count(*) as cnt
      from reviews
     ) r cross join
     (select sum(average) as suma, count(*) as cnt
      from dummy_reviews
     ) d;

实际上,我建议这不仅仅是因为你的评论。在某些情况下,这可能是性能更好的代码。