带连接查询的SQLCount

时间:2017-10-02 13:30:37

标签: mysql hibernate

我正在使用angularjs.I我试图通过使用连接查询来显示计数。我有三个表。它的结构如下所示

募捐

    fundraiserId  
     1

fundraisingusers

    fundraisinguserId  userId fundraiserId
        1                  1         1

用户

        userId //and other columns 
           1

现在我正在编写类似这样的查询

SELECT f.fundraiserId 
     , fu.userId 
  FROM fundraisers f 
  LEFT 
  JOIN fundraisingusers fu 
    ON f.fundraiserId = fu.fundraiserId 
  LEFT 
  JOIN users u 
    ON fu.userId = u.userId;

现在在前面的html我想显示用户数量,即筹款用户表中的用户数量。在这种情况下1.但现在我不知道如何在连接查询中计数。目前我得到userId 。我需要将其显示为计数而非Id。

这是我的HTML

    <div class="col-xs-6 col-sm-4 col-md-4" data-ng-repeat="fundraise
    in fundraises">
    <span class="glyphicon glyphicon-thumbs-up"></span>Supporters
    <h6>{{fundraise.userId}}</h6>//Here i need count of users from fundraisingusers table but i am getting userId
    </div>

这是我用来显示数据的POJO类

    public class Fundraisers implements Serializable{
    private Integer fundraiserId;
    private Integer userId;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "fundraiserId")
    public Integer getFundraiserId() {
    return fundraiserId;
    }
    public void setFundraiserId(Integer fundraiserId) {
    this.fundraiserId = fundraiserId;
    }

    @Transient
    @JoinColumn(insertable=false,updatable=false)
    public Integer getUserId() {
    return userId;
    }
    public void setUserId(Integer userId) {
    this.userId = userId;
    }

这是我的数据库访问代码

    @Override
    public List<Fundraisers> getFundsByIndexWithStatusForFront() 
    {
      List<Fundraisers> fundRaisers = new ArrayList<Fundraisers>();
      Query query = 
      sessionFactory.getCurrentSession().createSQLQuery(FUNDRAISES);//Here i am using above query
    query.setResultTransformer(Transformers.aliasToBean(Fundraisers.class));
        fundRaisers = query.list();
        return fundRaisers;
     }

任何人都可以告诉我如何获得userId而不是userId?

3 个答案:

答案 0 :(得分:-1)

尝试使用GROUP BY并使用count():

SELECT f.fundraiserId as fundraiserId,
       CAST(count(fu.userId) AS CHAR) as userId 
FROM fundraisers as f 
     left outer join fundraisingusers as fu on f.fundraiserId =fu.fundraiserId 
     left outer join users as u on fu.userId = u.userId
group by f.fundraiserId;

答案 1 :(得分:-1)

SELECT f.fundraiserId as fundraiserId,COUNT(fu.userId) as userId 
FROM
fundraisers f 
left outer join fundraisingusers fu on
f.fundraiserId = fu.fundraiserId 
left outer join users u on fu.userId = u.userId";

答案 2 :(得分:-1)

 SELECT COUNT(fu.userId) as userId ,

此函数返回用户数 正确的查询:

SELECT f.fundraiserId as fundraiserId,COUNT(fu.userId) as userId FROM
fundraisers as f left outer join fundraisingusers as fu on
f.fundraiserId = fu.fundraiserId left outer join users as u on
fu.userId = u.userId";