在mysql中加入两列

时间:2016-04-23 12:50:09

标签: mysql sql database join

我想在表a中添加表b中的数据,但遗憾的是全外连接在mysql中不起作用。我也尝试过联盟,但它会抛出错误,因为我的语句有分组依据和按关键字排序

SELECT COUNT( ReviewedBy ) AS TotalReviews, OrganizationId, SUM( Rating ) AS TotalStars, COUNT( Rating ) AS TotalRatings, (
       SUM( Rating ) / COUNT( Rating )
          ) AS AverageRating
        FROM  `tbl_reviews` 
      WHERE ReviewType =  'shopper'
      AND ReviewFor =  'org'
       AND OrganizationId
               IN (

           SELECT OrganizationId
         FROM tbl_organizations
         WHERE CategoryID =79
          )
        GROUP BY OrganizationId
        ORDER BY AverageRating DESC 

This is what i'm getting from the above statement

我想在结果中获得organizationId 21数据,但我没有得到结果,因为它没有出现在< tbl_review'表 click here to see the table b

我如何获得所需结果?

2 个答案:

答案 0 :(得分:1)

你不需要一个完整的,但是左边的加入:

SELECT COUNT( ReviewedBy ) AS TotalReviews, o.OrganizationId, 
   SUM( Rating ) AS TotalStars, COUNT( Rating ) AS TotalRatings, 
   (SUM( Rating ) / COUNT( Rating )) AS AverageRating
FROM tbl_organizations AS o
LEFT JOIN `tbl_reviews` AS r
  ON o.OrganizationId = r.OrganizationId
 AND ReviewType =  'shopper' -- conditions on inner table 
 AND ReviewFor =  'org'      -- must be moved to ON
WHERE CategoryID =79
GROUP BY o.OrganizationId
ORDER BY AverageRating DESC 

为什么不使用AVG代替SUM/COUNT

答案 1 :(得分:0)

你试过了吗?

from organization
left outer join tbl_reviews
on organization.ID = tbl_reviews.organization is

你的where子句?在这种情况下,我认为你不需要一个完整的外连接......左外连接应该