How to Count Conditional Records with MyBatis and MySQL

This article shows how to use MyBatis XML mappers to write MySQL queries that count employees meeting specific criteria, such as those in the current month or before today, while explaining required aliasing and date‑format handling.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
How to Count Conditional Records with MyBatis and MySQL

Scenario

The business table stores records for all employees, and the goal is to count how many records satisfy certain conditions up to the current moment, for example the number of employees meeting the criteria in the current month.

Implementation for the Current Month

A MyBatis <select> statement can be defined to count distinct employee numbers (gh) for the current month:

<select id="selectCurrentMonthNum" resultType="Integer">
    SELECT count(*) FROM (
        SELECT gh FROM dp_ddjl
        WHERE sh = 1 AND sfcl = 1 AND htsfcl = 1
          AND date_format(ddsj,'%y%m') = date_format(#{currnetMonth},'%y%m')
        GROUP BY gh
    ) a
</select>

Note that the outer query must be given an alias (here a). The column gh represents the employee number used for classification. The parameter currnetMonth supplies the current date, from which the month part is extracted.

Implementation for Counting Up to Today

Another <select> statement counts records whose end date is earlier than today:

<select id="selectHtDqNum" resultType="Integer">
    SELECT count(*) FROM (
        SELECT gh FROM ht_htcx
        WHERE isdelete = 0
          AND date_format(#{today},'%y%m%d') > date_format(jssj,'%y%m%d')
        GROUP BY gh
    ) a
</select>

This query filters out deleted rows ( isdelete = 0) and compares the formatted dates to ensure only records ending before the supplied today value are counted.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSQLMySQLMyBatisCount Query
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.