Foreign key
Foreign key column can contain NULL to indicate no relationship.
如果外键为NULL值,就表示没有关系
coalesce()函数
①用途:
将空值替换成其他值
返回第一个非空值
The coalesce() function can be useful for specifying a default or backup value when a column contains NULL values.
coalesce() checks arguments in order and returns the first non-NULL value, if one exists.
coalesce(NULL, 1, 2) = 1
coalesce(NULL, NULL) = NULL
coalesce(2, 3, NULL) = 2
②表达式:
COALESCE是一个函数, (expression_1, expression_2, …,expression_n)依次参考各参数表达式,遇到非null值即停止并返回该值。如果所有的表达式都是空值,最终将返回一个空值。使用COALESCE在于大部分包含空值的表达式最终将返回空值。
例子:
industry, sector都有可能是空值,那要定位每个公司在fortune500中的行业属性,要找到industry或sector的第一个非空值就行
-- 参数说明:如果industry==null,则选择sector;如果industry!=null,则选择industry;如果a b c 都为null ,则返回为则显示'Unknown'。
SELECT coalesce(industry, sector, 'Unknown') AS industry2,
-- Don't forget to count!
count(*) AS count
FROM fortune500
-- Group by what? (What are you counting by?)
GROUP BY industry2
-- Order results to see most common first
ORDER BY count DESC
-- Limit results to get just the one value you want
LIMIT 1;
这个参数使用的场合为:假如某个字段默认是null,你想其返回的不是null,而是比如0或其他值,可以使用这个函数
SELECT COALESCE(field_name,‘Unknow’) as value from table;