SQL-没有评论时,order by破坏了我的查询

时间:2018-06-26 21:15:49

标签: mysql sql

我有下面列出的相当长的SQL查询。如您所见,它是通过AvgRating和NumReviews进行排序的,它们均依赖于来自reviews表的数据。不幸的是,即使没有评论,我也需要查看结果中的行,当前,如果届时没有要订购的评论,则该行不会显示在结果中。感谢所有帮助。

SELECT travisor_tradesperson.name, travisor_tradesperson.id, travisor_catagory.catname, 
                    travisor_company.cname, travisor_company.description, travisor_company.city, travisor_company.address, travisor_company.postcode, travisor_company.phone, 
                    ROUND(AVG(travisor_review.rating)) as RoundAvgRating, AVG(travisor_review.rating) as AvgRating, COUNT(travisor_review.rating) as NumReviews
            FROM `travisor_tradesperson`
            INNER JOIN travisor_company 
            ON travisor_tradesperson.company = travisor_company.id
            INNER JOIN travisor_catagory 
            ON travisor_tradesperson.catagory = travisor_catagory.id        
            INNER JOIN travisor_review 
            ON travisor_review.tradesperson = travisor_tradesperson.id 
            WHERE travisor_catagory.catname = '$catagory'
            AND travisor_company.city = '$city'
            GROUP BY travisor_tradesperson.name, travisor_catagory.catname, travisor_company.cname, 
                travisor_company.description
            ORDER BY AvgRating DESC, NumReviews DESC

1 个答案:

答案 0 :(得分:3)

左联接travisor_review而不是内部联接。内部联接将仅查找两个表中都存在的记录。如果您对该商人记录没有任何评论,它将从结果集中删除。

如果左联接不能与联接谓词匹配,则它将返回NULL。在这种情况下,商人将返回但带有NULL。如果需要,将NULL转换为0,这应该可以修复您的AVG。