java MySQL的in查询两个字段同时相等的多个数据查询

在Java中想进行下面的查询,不想写循环一条条查

select id,name,address,age  from users where name='A'  and  address='addr1'

select id,name,address,age  from users where name='B'  and  address='addr2'

select id,name,address,age  from users where name='C'  and  address='addr3'

查了下,in可以使用在多个字段上

select id,name,address,age  from users where (name,address) in(('A','addr1'),('B','addr2'),('C','addr3'))

在Java中

1.构建条件

List<Map<String, String>> list = new ArrayList<>();  
// 创建一个新的Map对象  
Map<String, String> map1 = new HashMap<>();  
map1.put("name", "A");  
 map1.put("address", "addr1");  
list.add(map1);  
Map<String, String> map2= new HashMap<>();  
map2.put("name", "B");  
 map2.put("address", "addr2");  
list.add(map2);  
Map<String, String> map3= new HashMap<>();  
map3.put("name", "C");  
 map3.put("address", "addr3");  
list.add(map3);  

2.mapper接口定义

List<Map<String,Object>> getInfos(@Param("list")List<String> list);

3.mapper XML

<select id="getInfos" resultType="java.util.HashMap">
        select id,name,address,age
        from `users`
        where (name,address) in
        <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
            (#{item.name},#{item.address})
        </foreach>
</select>

这样就可以一次查询出来了

 

posted @ 2024-05-11 23:27  慕尘  阅读(277)  评论(0编辑  收藏  举报