mybatis 查询结果集 case when
时间: 2023-09-27 21:08:06 浏览: 159
MyBatis allows you to use the `case when` statement in your SQL queries to handle conditional logic in the result set. Here's an example of how you can use it:
```xml
<select id="getUsers" resultType="User">
SELECT id, name,
CASE
WHEN age < 18 THEN 'Minor'
WHEN age >= 18 AND age < 65 THEN 'Adult'
ELSE 'Senior'
END AS age_group
FROM users
</select>
```
In this example, we have a `users` table with columns `id`, `name`, and `age`. The `age_group` column is derived using the `case when` statement. If the age is less than 18, it will be labeled as 'Minor'. If the age is between 18 and 65, it will be labeled as 'Adult'. Otherwise, it will be labeled as 'Senior'.
You can define the SQL query in the MyBatis XML mapping file or use annotations if you're using MyBatis annotations. The resultType should be set to the appropriate Java class that matches the result set.
Hope this helps! Let me know if you have any further questions.
阅读全文