mysql多字段in用法

文章目录

    • 前言
    • mysql多字段in写法
    • mybatis多字段in写法

前言

经常在写sql语句的时候会用到in的用法,以下内容讲解多个字段如何同时使用in,以下内容基于mysql 8.0进行讲解。

mysql多字段in写法

需求:
查询用户表中姓名=张三,年龄11岁及姓名=李四,年龄12岁的用户

普通写法:

select * from user where (user_name = '张三' and age = 11) or (user_name = '李四' and age = 12);

sql示例1:

select * from user where (user_name,user_age) in (('张三',11),('李四',12));

说明:以上语句查询是否存在姓名为张三,年龄11及姓名李四,年龄12岁的用户

sql示例2:

select * from user where (user_name,user_age) in (select user_name,user_age from user_info where user_name = '张三');

说明:当in后面的内容是另一个select查询的结果,只需要查询结果的外面有括号即可,如上图所示

mybatis多字段in写法

dao层:

List<UserDto> selectByUserNameAndAge(List<User> list);

mapper.xml

<select id="selectByUserNameAndAge" resultMap="UserMap" parameterType="java.util.List">
    select *
    from user
    where (user_name,user_age) in (
    <foreach collection="list" item="item" separator=",">
      (#{item.user_name},#{item.user_age})
    </foreach>
    )
  </select>

你可能感兴趣的:(数据库,mysql,数据库,sql,mysql多字段in用法)