简体   繁体   English

获取此结果的SQL查询

[英]Sql query to get this result

Consider i have a user table and I have three columns mobilePhone , homePhone and workPhone ... 考虑我有一个user表,我有三列mobilePhonehomePhoneworkPhone ...

I have to select homePhone for every user as first pref 我必须为每个用户选择homePhone作为第一个pref
if there is no value 如果没有价值
I'll go for mobilePhone and 我会选择mobilePhone
if there is no value for it 如果它没有价值
I ll go for workPhone .... 我会去workPhone ....

Any suggestion how it can be done in mysql.. 有任何建议如何在mysql中完成..

Try using Sql Server COALESCE (Transact-SQL) , 尝试使用Sql Server COALESCE(Transact-SQL)

Returns the first nonnull expression among its arguments. 返回其参数中的第一个非空表达式。

Same goes for MySql COALESCE(value,...) MySql COALESCE也是如此(值,......)

Returns the first non-NULL value in the list, or NULL if there are no non-NULL values. 返回列表中的第一个非NULL值,如果没有非NULL值,则返回NULL。

Something like 就像是

SELECT  COALESCE(homePhone, mobilePhone, workPhone) ContactPhone
FROM    Users

You want the Coalesce function which returns the first non-null value: 您需要Coalesce函数,它返回第一个非null值:

Select Coalesce(homephone, mobilephone, workphone) Phone
From `user`

Coalesce does exist in MySQL. Coalesce确实存在于MySQL中。 It is an ANSI defined function. 它是ANSI定义的函数。

Coalesce function (MySQL). 合并功能(MySQL)。

SELECT user, homePhone 
FROM user
WHERE homePhone != ''

UNION

SELECT user, mobilePhone 
FROM user
WHERE homePhone = '' AND mobilePhone != ''

UNION 

SELECT user, workPhone 
FROM user
WHERE homePhone = '' AND mobilePhone = ''

您可以使用嵌套的IF语句或CASE ,也可以使用业务逻辑层执行此作业

Another solution is to use the following SQL: 另一种解决方案是使用以下SQL:

ISNULL(ISNULL(HomePhone,MobilePhone),WorkPhone) AS Phone

Thanks, Nirmal 谢谢,Nirmal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM