如何从列表中获取不在数据库表的特定列中的值

问题描述 投票:0回答:1

我正在使用 Spring Boot 3、Java 17 和 mariaDB。

我有一个列表 nameList = {"alice", "bob", "john", "tom"}。在数据库中,我还有一个表T,其中有两列ab。表格如下所示。

一个 b
爱丽丝 30
鲍勃 50
麦克 20
齐亚 10

我想使用 nameLista 列中搜索,这将为我提供 nameList 中不在 a 列中的名称。

预期结果将是一个列表 结果 = {"约翰", "汤姆"}

我无法编写正确的 JPQL。

请注意,我不想进行后期处理。例如,通过编写

select t.a from T t where t.a in :nameList
,我首先找到{“alice”,“bob”},然后将其从nameList中排除(后处理),我可以得到预期的输出。我希望查询能够处理一切。

java spring-boot mariadb jpql
1个回答
0
投票

最好的方法是查找列表中的行,然后在客户端中排除列表中的行。

我不知道 JPQL 能做什么,但如果你 had 在 mariadb 中做到这一点,你会这样做:

select searching.a
from ((select a from T limit 0) union all (values ('alice'),('bob'),('john'),('tom'))) searching
where not exists (select 1 from T where T.a=searching.a)

(select a from T limit 0)
只是提供子查询结果列的名称和类型; mariadb 和 mysql 提供默认列名,但两者之间存在差异,尤其是 mariadb 没有帮助。

在 mysql 中,值表构造函数需要在每行值之前添加

ROW

select searching.a
from ((select a from T limit 0) union all (values row('alice'),row('bob'),row('john'),row('tom'))) searching
where not exists (select 1 from T where T.a=searching.a)

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.