如何在mysql中使用sql一样的情况?

时间:2015-03-27 11:50:54

标签: php mysql

我正在尝试以

进行MySQL查询
SELECT distinct FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(DateAndTime)/(60*2))*(60*2)) as DateAndTime,
       (CASE WHEN TagName like '%AHU-204\CV' THEN Val END) AS Tag0 
       from view1 
       where (view1.DateAndTime between "2014-12-03 11:30" AND "2014-12-03 13:00") 
       GROUP BY DateAndTime

它正确地提取DateAndTime列,但不是从表中提取值,而是在NULL列中显示Tag0。我的view1的Val列中存在值。

1 个答案:

答案 0 :(得分:0)

没有else的情况会在没有条件匹配的情况下发布NULL值,在你的情况下,当TagName与like命令不匹配时,它会将NULL发送到Tag0。

示例1: 如果案例不匹配(原始查询)

,则会将null发布到tag0
SELECT distinct FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(DateAndTime)/(60*2))*(60*2)) as DateAndTime,
(CASE WHEN TagName like '%AHU-204\CV' THEN Val END) AS Tag0 from view1 
where (view1.DateAndTime between "2014-12-03 11:30" AND "2014-12-03 13:00") 
GROUP BY DateAndTime

如果您只需要收集那些符合相似条件的值,那么将条件移动到WHERE子句

示例2: 移动'案例'从select到WHERE子句。如果条件不匹配,则不会发布到结果中。

SELECT distinct FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(DateAndTime)/(60*2))*(60*2)) as DateAndTime, 
TagName AS Tag0 from view1 
where (view1.DateAndTime between "2014-12-03 11:30" AND "2014-12-03 13:00") AND UPPER(TagName) like UPPER('%AHU-204\CV') 
GROUP BY DateAndTime

注意TagName和表达式上的upper()以强制区分大小写。

如果您需要多个匹配项,可以在where子句中设置多个案例:

示例3: 使用" OR"匹配多个模式在WHERE子句

SELECT distinct FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(DateAndTime)/(60*2))*(60*2)) as DateAndTime,
TagName AS Tag0 from view1
where (view1.DateAndTime between "2014-12-03 11:30" AND "2014-12-03 13:00") AND 
(UPPER(TagName) like UPPER('%AHU-204\CV') OR UPPER(TagName) like UPPER('%CTH-506\ST%'))
GROUP BY DateAndTime

或添加WHERE Tag0 IS NOT NULL:

示例4: 使用示例1查询并删除Tag0为空的结果

SELECT DateAndTime, Tag0 FROM (
    SELECT distinct FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(DateAndTime)/(60*2))*(60*2)) as DateAndTime,
    (CASE WHEN UPPER(TagName) like '%AHU-204\CV' THEN Val END) AS Tag0 from view1 
    where (view1.DateAndTime between "2014-12-03 11:30" AND "2014-12-03 13:00")
    GROUP BY DateAndTime) AS Derived 
WHERE Tag0 IS NOT NULL;

另外,如果你想尝试匹配ahu-204 \ CV'使用'%AHU-204 \ CV',您可以根据您的字符集获得区分大小写问题。 在这种情况下,尝试匹配UPPER(TagName),例如'%AHU-204 \ CV'并且您将获得不区分大小写的匹配。