<?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.ruoyi.web.sales.mapper.RelCustomerMarketMapper">

    <!--
      分页一次 JOIN 出展示字段，避免主表分页后再对 customer/line/market 多次 IN 查询。
      建议在 rel_customer_market 上建立组合索引，见 sql/rel_customer_market_index_page.sql
    -->
    <select id="selectCustomerMarketPage" resultType="com.ruoyi.web.sales.domain.RelCustomerMarket">
        SELECT
            r.id,
            r.org_id AS orgId,
            r.line_num AS lineNum,
            r.market_num AS marketNum,
            r.customer_num AS customerNum,
            CASE WHEN c.id IS NOT NULL THEN c.remark ELSE r.remark END AS remark,
            r.del_flag AS delFlag,
            r.create_by AS createBy,
            r.create_time AS createTime,
            r.update_by AS updateBy,
            r.update_time AS updateTime,
            c.customer_name AS customerName,
            c.customer_level AS customerLevel,
            c.receivable_customer AS receivableCustomer,
            c.payee_customer AS payeeCustomer,
            c.credit_control AS creditControl,
            c.customer_channel AS customerChannel,
            l.line_name AS lineName,
            m.market_name AS marketName
        FROM rel_customer_market r
        LEFT JOIN base_customer c
            ON c.org_id = r.org_id
            AND c.customer_num = r.customer_num
            AND c.del_flag = '0'
        LEFT JOIN base_line l
            ON l.org_id = r.org_id
            AND l.line_num = r.line_num
            AND l.del_flag = '0'
        LEFT JOIN base_market m
            ON m.org_id = r.org_id
            AND m.market_num = r.market_num
            AND m.del_flag = '0'
        WHERE r.org_id = #{orgId}
          AND r.del_flag = '0'
        <if test="lineNum != null and lineNum != ''">
            AND r.line_num = #{lineNum}
        </if>
        <if test="marketNum != null and marketNum != ''">
            AND r.market_num = #{marketNum}
        </if>
        ORDER BY r.id DESC
    </select>

</mapper>
