灵感来了也记不住,在这里记录一下一些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>