複雜sql記錄

靈感來了也記不住,在這裏記錄一下一些sql查詢,方便以後複製粘貼

往角色爲st_admin的用戶的user_msg表中插入一條記錄。
難點:角色爲st_admin的用戶個數不定

<insert id="sendMsgToRole">
    insert into user_msg
    (user_id,title,content,sender)
    select tmp.*,
        #{title},
        #{content},
        #{sender} from
    (select user_id from user_role ur
            left join role r
            on ur.role_id=r.id
            where r.role_name=#{role}
    ) tmp
</insert>

往ids這一羣用戶的user_msg表中插入一條記錄,並更新他們的消息提示狀態;
如果ids爲null,則往全體用戶發送該消息。
難點:如果發送目標爲全體,則消息提示狀態需要更新全體,如果發送目標限制於ids,則消息提示狀態僅更新該類用戶。

foreach遍歷的collection直接填寫傳遞過來的集合名稱即可,不用el表達式

<insert id="sendMsg">
    insert into user_msg (user_id,title,content,sender)
        select
      u.id,
            #{title},
            #{content},
            #{sender}
        FROM user u
        <choose>
            <when test="ids !=null and ids.size>0">
                where u.id
                <foreach collection="ids" item="id" open="in(" close=")" separator=",">
                    #{id}
                </foreach>
                ;
                update user set msg_status=1
                where user.id
                <foreach collection="ids" item="id" open="in(" close=")" separator=",">
                    #{id}
                </foreach>
            </when>

            <otherwise>
            ;
                update user set msg_status=1;
            </otherwise>
        </choose>
</insert>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章