douchongbc72264 2014-01-14 12:35
浏览 79
已采纳

使用join的构建一个mysql查询,以便在symfony中使用

DB struct:

DB Struct

DB description

One comapny can have review (0,1 or more) review always have reviews_item all reviews_item have one category

Problem

I need SQL query that makes list of 'company's with AVG value of reviews_items.value, i need it to set order by this value. Even if for some 'company' i dont have any 'reviews' and 'reviews_items' comapny should be in list with AVG == 0. it should select companies only with active == 1 and (if exists) review active==1

My slq query, dont work propertly:

SELECT 
    c.name,c.logo,c.url,
    AVG(ri.value) as avarage
FROM company c
LEFT JOIN reviews r ON r.company_id = c.id
LEFT JOIN reviews_items ri ON ri.review_id = r.id
LEFT JOIN category cat ON ri.category_id = cat.id
WHERE c.active = 1
GROUP BY c.id

I hope that my problem is clear :)

PS. Sorry if my language (english) is not so good :D

  • 写回答

3条回答 默认 最新

  • donglvhe7591 2014-01-14 14:13
    关注

    There was missing sth in WERE clausule (OR r.active IS NULL):

    SELECT 
      c.name,c.logo,c.url,
      AVG(NULLIF(ri.value,0)) as avarage
    FROM company c
     LEFT JOIN reviews r ON r.company_id = c.id
     LEFT JOIN reviews_items ri ON ri.review_id = r.id
     LEFT JOIN category cat ON ri.category_id = cat.id
    WHERE c.active = 1 AND (r.active = 1 OR r.active IS NULL)
     GROUP BY c.id
    ORDER BY avarage  DESC
    

    Thanks for trying!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退