通过连接3个表来计算行数

时间:2012-10-01 04:22:23

标签: mysql

我的查询如下所示

select count(au.agentId), count(mr.agentId)
       from agents a
       left join assignunits au on au.agentId=a.id
       left join assignmarketreport mr on mr.agentId=a.id                        
       where a.adminsId='0' 
       and a.id='29' group BY `mr`.`agentId`, au.agentId ASC

我的count(au.agentId)值与count(mr.agentId)的值相同。

我想要的是什么:

以下示例数据

assignunits

agentId     status
     2      Y
     2      Y

assignmarketreport

agentId     status
     2      Y
     2      Y
     2      Y

代理商

agentId     adminsId
     2      0

现在count(mr.agentId)应该返回3
并且count(au.agentId)应该返回2

3 个答案:

答案 0 :(得分:2)

尝试以下方法,

SELECT  b.totalAgentUnits, c.totalAgentReport
FROM    Agents a
        LEFT JOIN
        (
            SELECT agentID, COUNT(agentID) totalAgentUnits
            FROM assignunits
            GROUP BY agentID
        ) b ON a.agentID = b.agentID
        LEFT JOIN
        (
            SELECT agentID, COUNT(agentID) totalAgentReport
            FROM assignmarketreport
            GROUP BY agentID
        ) c ON a.agentID = c.agentID

答案 1 :(得分:2)

试试这个:

 select au_agentId,mr_agentId 
  from 
          (select a.agentId,count(au.agentId) as au_agentId  
           from   agents a
           left join assignunits au 
           on     au.agentId=a.agentId
           where  a.adminsId='0'
           group  by a.agentId )au
      join
      (select a.agentId,count(mr.agentId) as mr_agentId   
       from   agents a
           left join assignmarketreport mr 
           on    mr.agentId=a.agentId
           where a.adminsId='0'
           group by a.agentId)mr  
      on    au.agentId=mr.agentId       


SQl fiddle demo

答案 2 :(得分:1)

首先查询3个计数count(units), count(marketport),count(agents)并将其插入计数

count(counts `count(units), count(marketport),count(agents)`)

之后你可以设置一个php循环来获取每个数据并显示在每个表中

for($i=0;$count<3;$i++){
if($i==1){
//table 1
}
elseif($i==2){
//table 2
}
elsE{
//last table
}
}

意见只是谢谢