MySQL query - how to return placeholder value instead of NULL if no entry found

寵の児 提交于 2019-12-11 09:35:06

问题


Let's say I have a table called references, which has two fields: an id and a reference field.

I want to create a query that will provide me with a reference number based upon an id. Like this:

SELECT reference 
  FROM references 
 WHERE id = x 

(where x is some integer)

However if the id is not found in the table I would like the query to show -1 instead of NULL.

How can I do this?

SELECT COALESCE(reference, -1) FROM references WHERE id = x 

doesn't work


回答1:


Here are a few approaches:

SELECT COALESCE(MAX(reference), -1)
  FROM references
 WHERE id = ...
;

SELECT COALESCE(reference, -1)
  FROM references
 RIGHT
 OUTER
  JOIN (SELECT 1 c) t
    ON id = ...
;

SELECT COALESCE
        ( ( SELECT reference
              FROM references
             WHERE id = ...
          ),
          -1
        )
;

(I'd go with the first one, personally, but all three work.)




回答2:


if subset has cardinality 0 (elements with id = 2), there is nothing to compare, there's certainity that such (id = 2) element doesn't exist. in the other hand, if you want to find, let's say, maximum element in that empty subset, you will get unknown value (every member of superset will be a supremum and infimum of the empty set)

i'm not sure if it's correct, but imho, quite logical



来源:https://stackoverflow.com/questions/12406647/mysql-query-how-to-return-placeholder-value-instead-of-null-if-no-entry-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!