How to return default value from SQL query

后端 未结 8 1887
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:25

Is there any easy way to return single scalar or default value if query doesn\'t return any row?

At this moment I have something like this code example:



        
8条回答
  •  青春惊慌失措
    2020-12-05 13:40

    If the query is supposed to return at most one row, use a union with the default value then a limit:

    SELECT * FROM 
     (
      SELECT Name FROM Users WHERE Id = @UserId`
      UNION
      SELECT 'John Doe' AS Name --Default value
     ) AS subquery
    LIMIT 1
    

    Both the query and default can have as many columns as you wish, and you do not need to guarantee they are not null.

提交回复
热议问题