Show query results for keys not found [MySQL]

后端 未结 1 376
深忆病人
深忆病人 2021-01-27 05:41

IF I am comparing 2 tables users [user_id, username] and user_comments [user_id, comment] where user_id are the

相关标签:
1条回答
  • 2021-01-27 06:18

    I think you want a left join:

    select coalesce(cast(uc.user_id as varchar(255)), 'unknown') as user_id,
           uc.comment
    from user_comments uc left join
         users u
         on u.user_id = uc.user_id;
    

    You do need to be careful about the type of user_id. Assuming it is not a string, you need to cast it to be compatible with 'unknown'. Otherwise, NULL is a fine non-matching value.

    0 讨论(0)
提交回复
热议问题