mysql - Reuse result of IF condtion in true or false result expression -
i have following nested query:
select `messages`.*,      if((select `status` messages_status          messages_status.message_id = messages.id , user_id = 149) null,          'unread', messages_status.status) `status` `messages`  what do, if there no messages_status.status set (i.e. if null), should return 'unread'. however, if set, should return value.
currently, returns error: unknown column 'messages_status.status' in 'field list'
do have idea how fix this?
you can't refer result of if's condition in other places.  repeat query:
if((select `status` messages_status          messages_status.message_id = messages.id , user_id = 149) null,      'unread',      (select `status` messages_status          messages_status.message_id = messages.id , user_id = 149))     status but it's clearer use join instead:
select  m.* ,       coalesce(ms.status, 'unknown')    messages m left join         messages_status ms on      ms.message_id = m.id         , ms.user_id = 149 the coalesce function produces first of arguments not null.
Comments
Post a Comment