<?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.diagbot.mapper.RelationMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.diagbot.entity.Relation">
        <id column="id" property="id" />
        <result column="start_id" property="startId" />
        <result column="relation_id" property="relationId" />
        <result column="end_id" property="endId" />
    </resultMap>

    <select id="getAllRelation" resultType="com.diagbot.dto.RelationDTO">
        SELECT c.id, c.start_id, c.name as startName, c.type as startType, c.relation_id, d.name as relationName,
        e.end_id, e.name as endName, e.type as endType FROM
            (SELECT a.id, a.start_id, b.name, b.type, a.relation_id FROM relation a, library_info b
                WHERE b.is_concept = 1 and a.start_id = b.concept_id) c,
            lexicon_relationship d,
            (SELECT a.id, a.end_id, b.name, b.type FROM relation a, library_info b
                WHERE b.is_concept = 1 and a.end_id = b.concept_id) e
        WHERE c.id = e.id and c.relation_id = d.id ORDER BY c.id
    </select>

    <select id="getRelationbyName" parameterType="com.diagbot.vo.RelationVo" resultType="com.diagbot.dto.RelationDTO">
        SELECT c.id, c.start_id, c.relation_id, e.end_id FROM
            (SELECT a.id, a.start_id, a.relation_id FROM relation a, library_info b
                WHERE a.start_id = b.concept_id and b.name = #{start_term}) c,
            lexicon_relationship d,
            (SELECT a.id, a.end_id FROM relation a, library_info b
                WHERE a.end_id = b.concept_id and b.name = #{end_term}) e
        WHERE c.id = e.id and c.relation_id = d.id and d.name = #{relation_name}
    </select>

    <select id="getRelation" parameterType="com.diagbot.dto.RelationDTO" resultType="com.diagbot.dto.RelationDTO">
        SELECT id, start_id, relation_id, end_id
        FROM relation
        WHERE start_id = #{startId} AND end_id = #{endId}
    </select>

    <update id="truncateRelation">
        Truncate Table relation
    </update>

    <select id="getLimboRelation" resultType="com.diagbot.entity.Relation">
        SELECT id, start_id, relation_id, end_id FROM relation
        WHERE start_id NOT IN ( SELECT id FROM concept )
        OR end_id NOT IN ( SELECT id FROM concept )
    </select>
</mapper>
