红酒泡绿茶 2013-11-17 02:38
浏览 10
已采纳

如何返回所有行,即使它们在连接表中没有行

I have three tables, Users, Profiles and Requests. Only users that have created requests, will have a row in the requests table. But I still need to get all the users back and display the total number of requests, per user. I have worked out the query below, which only returns the users who have a record in the requests table, although I need all users and for it to return 0 for the users requests, if a matching row is not found.

 public function getAllUsers()
    {
        $select = $this->userRepository->select();
        $select->setIntegrityCheck(false)
               ->from('users', array('id', 'username', 'date_created', 'active', 'last_login', 'role'))
               ->join('profiles', 'users.id = profiles.user_id', array('profile_id' => 'id', 'first_name', 'last_name', 'email', 'avatar', 'on_mailing_list'))
               ->join('recommendation_requests', 'users.id = recommendation_requests.user_id', array('requests' => 'count(*)'))
               ->order('users.date_created ASC');
        return $this->userRepository->getAdapter()->fetchAll($select);
    }

What would I need to change so that it returns all users, even if they don't have any requests and returns 0 for the requests column, not the total number of requests. I've tried joinLeft, joinRight, joinInner....I'm not a SQL guy so I'm a little stumped.

  • 写回答

1条回答 默认 最新

  • dqhnp44220 2013-11-17 03:15
    关注

    Firstly to list all users use OUTER JOIN e.g. LEFT JOIN

    Secondly change

    COUNT(*)
    

    to

    COUNT(recommendation_requests.user_id)
    

    Because you're using an OUTER JOIN you always have at least one row in your resultset for each user and that is why COUNT(*) gives 1 instead of 0 for users that don't have any requests. Instead you need to count values of recommendation_requests.user_id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?