首页 > 解决方案 > 将 Arraylist 传递给 SQL 查询以获得所需的结果

问题描述

我写了一个这样的查询:

select agent_id,count(id) as agentCount from demo.table lst where lst.agent_id in(:idpList) group by agent_id order by agentCount ASC;

但这仅返回 idp List 中的 agent_id 我还想获取列表中但不在 demo.table 中的 id 并将计数返回为 0 。我无法弄清楚我该怎么做。

例如:列表:[20,17,16,15,50] 所以 50 不是表格,但我希望 50 包含在最终结果中。

我有两个数据库,我正在获取所有 agent_id 并将其存储在列表中,而在另一个数据库中,我有一个表存储 id 和与这些 id 关联的任务的编号,所以我想检查对应于创建任务的次数这些agent_id并获取计数,但由于这些agent_id中的一些存在于第二个数据库表中,但有些则不是,因为不存在的计数应该返回0,但从这个查询中我得到的只是那些存在于第二个数据库表

帮助将不胜感激。

标签: javasqldatabaseparametershql

解决方案


尝试这个:

select count(*),A.agent_id from 
(
select 20 as agent_id
union select 17
union select 16
union select 15
union select 50 ) as A  LEFT JOIN demo.table s on s.agent_id = A.agent_id where s.agent_id in(:idpList)  group by s.agent_id;  

但是您必须手动创建查询的这一部分( select 20 as agent_id union select 17 union select 16 union select 15 union select 50 )。

否则没有办法做到这一点。


推荐阅读