<resultMap id="treeListResult" type="TreeListVo"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="parent_id" property="parentId"/> <result column="sort" property="sort"/> <collection property="children" ofType="TreeListVo"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="parent_id" property="parentId"/> <result column="sort" property="sort"/> <collection property="children" ofType="TreeListVo"> ... </collection> </collection> </resultMap>sql怎么写
时间: 2023-07-03 12:13:58 浏览: 41
假设你的树形结构表名为 `tree`,包含字段 `id`、`name`、`parent_id`、`sort`,其中 `id` 是主键,`parent_id` 是父节点的 ID,根节点的 `parent_id` 为 null。根据上面的 `resultMap` 配置,一对多查询的 SQL 可以这样写:
```sql
SELECT *
FROM tree t1
LEFT JOIN tree t2 ON t1.id = t2.parent_id
WHERE t1.parent_id IS NULL
ORDER BY t1.sort, t2.sort
```
这个 SQL 查询出所有根节点及其子节点,按照根节点的 `sort` 字段升序排列,子节点按照其 `sort` 字段升序排列。其中,`t1` 表示根节点,`t2` 表示子节点。`LEFT JOIN` 保证即使某个根节点没有子节点,仍然能查询出来。
注意,如果树很大,这个查询可能会很慢,需要根据实际情况进行优化,例如增加索引等。
相关问题
<resultMap id="eqMapVo" type="EquipmentVo"> <result property="eqId" column="eq_id"/> <result property="companyId" column="company_id"/> <result property="itemName" column="item_name"/> <result property="eqName" column="eq_name"/> <result property="serialNumber" column="serial_number"/> <collection property="maps" javaType="Map"/> </resultMap>中,maps的字段如何指定
在 `<collection>` 标签中,通过 `property` 属性指定集合属性的名称,这里是 `maps`。而 `javaType` 属性指定集合中元素的类型,这里是 `Map`,表示该集合中的元素是 `Map` 类型。如果查询结果中包含了与 `maps` 集合相关的列,可以在 `<collection>` 标签中通过 `<result>` 标签来映射这些列到 `Map` 对象的属性上。例如,如果查询结果中包含了 `key` 和 `value` 两列,可以通过如下方式将它们映射到 `Map` 对象的属性上:
```
<collection property="maps" javaType="Map">
<result column="key" property="key"/>
<result column="value" property="value"/>
</collection>
```
这样,在映射查询结果时,每行记录中的 `key` 和 `value` 列的值都会被封装成一个 `Map` 对象,并添加到 `maps` 集合中。
<id column="value" property="value"/>报错
非常抱歉,我之前的回答有误。在使用动态SQL片段时,`<id>` 元素是不需要的,因为我们只是想获取一列数据而不是主键。请修改你的代码如下:
```xml
<resultMap id="PinResultMap" type="java.lang.String">
<result column="value" property="value"/>
</resultMap>
<select id="getDistinctPin1" resultMap="PinResultMap" parameterType="com.example.pmp.pojo.dto.sense.senseDataDto">
<include refid="distinctQuery">
<property name="column" value="FAI_26_1_Value"/>
</include>
</select>
<select id="getDistinctPin2" resultMap="PinResultMap" parameterType="com.example.pmp.pojo.dto.sense.senseDataDto">
<include refid="distinctQuery">
<property name="column" value="FAI_26_2_Value"/>
</include>
</select>
<select id="getDistinctPin3" resultMap="PinResultMap" parameterType="com.example.pmp.pojo.dto.sense.senseDataDto">
<include refid="distinctQuery">
<property name="column" value="FAI_26_3_Value"/>
</include>
</select>
```
这样,你就可以正确地将查询结果映射到 `String` 类型的属性 `value` 上,并且不需要 `<id>` 元素。再次对之前的错误表示抱歉,希望这次回答能够解决你的问题。如果还有其他问题,请随时提出。