case when的使用-解决分表查数据给某一个字段

一个表中存的是目前有效的菜单,另外一个表中存的是有效菜单的历史更改数据 需要查询历史数据的时候,带上访问的历史数据菜单名称

SELECT
msg.msg_id,
msg.from_user_name,
msg.msg_type,
msg.url,
msg.EVENT,
msg.event_key,
(
SELECT wm.name
FROM wx_menu wm
WHERE wm.url = msg.event_key
) as ticket,
case when (
SELECT wm.name
FROM wx_menu wm
WHERE wm.url = msg.event_key
) is null then
( SELECT wm_log.name
FROM wx_menu_log wm_log
WHERE wm_log.url = msg.event_key
order by created desc limit 1
)
else (
SELECT wm.name
FROM wx_menu wm
WHERE wm.url = msg.event_key
) end
as newTicket,
msg.text_match_flag,
msg.text_match_content,
msg.created
FROM wechat_message msg
where
msg.from_user_name="XXXXX"
order by msg.created desc

posted @ 2018-08-13 10:55  乔胖胖  阅读(1060)  评论(0编辑  收藏  举报