使用三个表查询SQL数据

时间:2013-08-29 09:55:03

标签: mysql sql sql-server-2008

我试图通过查看CategoryBusinessMapping和Review Rating表来检索CategoryID和CategoryName。我正在尝试检索以下类别表的数据:

Category     ParentCategoryID     CategoryName
1            null                 Education
2            1                    School
3            null                 Health
4            3                    Doctors
5            1                    Colleges

我有商家表,其中包含BusinessID,BusinessName和BusinessDescription,如下所示:

BusinessID     BusinessName     BusinessDescription
YP00001        XYZ              ABCD
YP00002        ABC              XYZA

我有 CategoryBusinessMapping 表,如下所示:

MappingID     CategoryID     BusinessID
1             1              YP00001
2             2              YP00001
3             5              YP00001
4             3              YP00002
5             4              YP00002

我有这个映射表来映射不同类别的业务。我也有评级表,如下所示:

RatingID     BusinessID
1            YP00001
2            YP00001
3            YP00001
4            YP00002
5            YP00002

在此表中,我假设具有相同BusinessID的记录属于最受欢迎的Business。这意味着,上面的商业ABCD ID = YP00001在评级表中有四条记录。因此它属于最受欢迎的商业。同样,YP00002与YP00001相邻。通过按降序查看最受欢迎的业务,我想检索CategoryName和CategoryID。我试过这个只从Rating表中检索:

select   Distinct ReviewRating.BusinessID
         ,Count(*)as Rating
from     YP.utblYPReviewRatingDtls as ReviewRating
group by ReviewRating.BusinessID 
order by Rating desc

我试过这个:

  SELECT  distinct c.CategoryName, b.BusinessID
    FROM Category c
     INNER JOIN categoryBusinessMapping  cbm
     ON (c.CategoryID=cbm.CategoryID)
     INNER JOIN Business b 
    ON (cbm.BusinessID=b.BusinessID)
     LEFT JOIN Rating  r 
     ON (cbm.BusinessID=r.BusinessID)
     where c.ParentCategoryID is null 

但我得到的结果是多余的。我还从查询中删除了BusinessID,我得到了结果,但结果不正确。如何删除冗余并获得正确的输出?

1 个答案:

答案 0 :(得分:2)

使用join并从评分表中获取BusinessID的计数并订购结果

SELECT c.*, COUNT(r.BusinessID) AS bcount FROM Category  c
INNER JOIN CategoryBusinessMapping  cbm ON (c.Category=cbm.CategoryID)
INNER JOIN Business b ON (cbm.BusinessID=b.BusinessID)
LEFT JOIN Rating  r ON (cbm.BusinessID=r.BusinessID)
GROUP BY r.BusinessID
ORDER BY bcount DESC