<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.steady.datavie.mapper.SteadyDataViewLedgerMapper">

    <select id="selectLedgerTree" resultType="com.njcn.gather.steady.datavie.pojo.bo.SteadyDataViewLedgerRowBO">
        SELECT ledger.Id AS id,
               ledger.Pid AS parentId,
               ledger.Name AS name,
               ledger.Level AS level,
               ledger.Sort AS sort,
               (
                   SELECT COUNT(DISTINCT equipment.id)
                   FROM cs_ledger equipment_ledger
                            INNER JOIN cs_equipment_delivery equipment ON equipment.id = equipment_ledger.Id
                   WHERE equipment_ledger.State = 1
                     AND equipment_ledger.Level = 2
                     AND equipment.run_status &lt;&gt; 0
                     AND (equipment_ledger.Id = ledger.Id OR FIND_IN_SET(ledger.Id, equipment_ledger.Pids) &gt; 0)
               ) AS deviceCount,
               (
                   SELECT COUNT(DISTINCT line.line_id)
                   FROM cs_ledger line_ledger
                            INNER JOIN cs_line line ON line.line_id = line_ledger.Id
                            INNER JOIN cs_equipment_delivery equipment ON equipment.id = line.device_id
                   WHERE line_ledger.State = 1
                     AND line_ledger.Level = 3
                     AND line.status = 1
                     AND equipment.run_status &lt;&gt; 0
                     AND (line_ledger.Id = ledger.Id OR FIND_IN_SET(ledger.Id, line_ledger.Pids) &gt; 0)
               ) AS lineCount
        FROM cs_ledger ledger
        WHERE ledger.State = 1
        <if test="keyword != null and keyword != ''">
          AND (
              ledger.Name LIKE CONCAT('%', #{keyword}, '%')
              OR EXISTS (
                  SELECT 1
                  FROM cs_ledger child
                  WHERE child.State = 1
                    AND FIND_IN_SET(ledger.Id, child.Pids) &gt; 0
                    AND child.Name LIKE CONCAT('%', #{keyword}, '%')
              )
          )
        </if>
        ORDER BY ledger.Level ASC, ledger.Sort ASC, ledger.Name ASC
    </select>
</mapper>
