gpt4 book ai didi

php - 连接多个表并根据第一个表 ID 获取状态

转载 作者:行者123 更新时间:2023-11-29 08:03:38 25 4
gpt4 key购买 nike

代理数据库表

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";

我想根据 last_viewed 列显示驱动程序的事件和空闲状态。例如,agent_id 2 有三个驱动程序 (1,2,3),这 3 个驱动程序的 Last_viewed 列中有 1,0,0。所以,我想显示这样的输出:1 个事件和 2 个空闲...

enter image description here

最佳答案

试试这个,。

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

这里是SQLFiddle

关于php - 连接多个表并根据第一个表 ID 获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23155513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com