Php 连接多个表并根据第一个表id获取状态
代理数据库表Php 连接多个表并根据第一个表id获取状态,php,mysql,select,join,jointable,Php,Mysql,Select,Join,Jointable,代理数据库表 agent_id agent_name company_name -------- ---------- ----------- 1 AAA XXX 2 BBB YYY 3 CCC ZZZ 4 DDD XYZ 驱动程序数据库表 agent_id driver_id driver_name last_viewed -------
agent_id agent_name company_name
-------- ---------- -----------
1 AAA XXX
2 BBB YYY
3 CCC ZZZ
4 DDD XYZ
驱动程序数据库表
agent_id driver_id driver_name last_viewed
-------- ---------- ----------- -----------
2 1 EEE 1
2 2 FFF 0
2 3 GGG 0
1 4 HHH 0
3 5 III 1
3 6 JJJ 1
我想要这样的输出
Agent Details Driver details
1, AAA, 1 Drivers (0 active | 1 idle)
Company name
2, BBB, 3 Drivers (1 active | 2 idle)
Company name
3, CCC, 2 Drivers (2 active | 0 idle)
Company name
我试过下面这个问题
$sql="SELECT a.*,d.*, COUNT(d.driver_id) AS drivers_count FROM ta_agent a JOIN ta_drivers d USING(agent_id) GROUP BY a.agent_id";
我想根据上次查看的列显示驱动程序的活动和空闲状态。例如,代理_id 2有三个驱动程序(1,2,3),而这三个驱动程序在其上次_查看的列中有1,0,0。所以,我想显示这样的输出1活动和2空闲
这就是你所看到的吗
select
concat(
a.agent_id,' ',a.agent_name,' ',a.company_name
) as `Agent Details`,
concat(
COUNT(d.driver_id),' Drivers (',
' Active ',sum(d.last_viewed = 1)
,' | ',sum(d.last_viewed = 0 ),' idle ) '
)as `Driver details`
FROM AGENT a
LEFT JOIN DRIVER d USING(agent_id)
GROUP BY a.agent_id
UODATE:
从上次评论
我不想要驱动程序详细信息->我想要的1个驱动程序(活动0 | 1空闲)
驱动程序数->1个驱动程序,活动->0,空闲->1
试试这个
select a.agent_id, a.agent_name, a.company_name, ifnull(cnt_all,0) total_drivers,ifnull(cnt_active,0) active_drivers, ifnull(cnt_idle,0) idle_drivers
from agent a left join (select agent_id, count(*) cnt_all
from driver
group by agent_id) cnt on a.agent_id=cnt.agent_id
left join (select agent_id, count(*) cnt_idle
from driver
where last_viewed=0
group by agent_id) idle on a.agent_id=idle.agent_id
left join (select agent_id, count(*) cnt_active
from driver
where last_viewed=1
group by agent_id) active on a.agent_id=active.agent_id
这里是您应该提及的表格详细信息pls@jmail:我已更新了我的问题格式请使用字段名格式化您的输出您是否希望采用这种格式1,AAA,xxx,1 HHH 0
我希望采用这种格式1,ABC,XYZ公司2驱动程序(1个活动,0个空闲)
。我已经更新了我最近的结果。现在,我想根据上次查看的列添加活动、空闲状态。你可以分别拆分驱动程序的数量、活动和空闲状态吗?你可以拆分驱动程序的数量、活动和空闲状态吗?我没有得到。你可以提供一个视图它应该是什么样子。我不想要驱动程序详细信息->1个驱动程序(活动0 | 1空闲)
我想要驱动程序数量->1个驱动程序,活动->0,空闲->1
select a.agent_id, a.agent_name, a.company_name, ifnull(cnt_all,0) total_drivers,ifnull(cnt_active,0) active_drivers, ifnull(cnt_idle,0) idle_drivers
from agent a left join (select agent_id, count(*) cnt_all
from driver
group by agent_id) cnt on a.agent_id=cnt.agent_id
left join (select agent_id, count(*) cnt_idle
from driver
where last_viewed=0
group by agent_id) idle on a.agent_id=idle.agent_id
left join (select agent_id, count(*) cnt_active
from driver
where last_viewed=1
group by agent_id) active on a.agent_id=active.agent_id