Sql显示结果为零

时间:2013-12-25 15:53:56

标签: sql

我正在使用此查询从我的网站搜索。

SELECT A.article_title , 
( 
  (CASE WHEN A.article_title LIKE '%earn%' THEN 1 ELSE 0 END ) 
+ ( CASE WHEN A.article_title LIKE '%facebook%' THEN 1 ELSE 0 END )) AS count 
FROM site_articles A
A.article_id ORDER BY count DESC
它向我展示了流动的结果..

article_title                           count
Earn From facebook                        2
Earn From adsense                         1
how to work online                        0
making money tips                         0

它还显示了“0”计数的结果。

我怎样才能防止它。

2 个答案:

答案 0 :(得分:5)

只需在WHERE中排除这些行,并且根本不计算它们。

SELECT A.article_title,
       ( ( CASE
             WHEN A.article_title LIKE '%earn%' THEN 1
             ELSE 0
           END ) + ( CASE
                       WHEN A.article_title LIKE '%facebook%' THEN 1
                       ELSE 0
                     END ) ) AS count
FROM   site_articles A
WHERE  A.article_title LIKE '%earn%'
        OR A.article_title LIKE '%facebook%'
ORDER  BY count DESC 

或者可能效率较低但可维护性较高的替代方法是将查询放在派生表中

SELECT *
FROM   (SELECT A.article_title,
               ( ( CASE
                     WHEN A.article_title LIKE '%earn%' THEN 1
                     ELSE 0
                   END ) + ( CASE
                               WHEN A.article_title LIKE '%facebook%' THEN 1
                               ELSE 0
                             END ) ) AS Count
        FROM   site_articles A) T
WHERE  T.Count > 0 

答案 1 :(得分:2)

例如,

SELECT A.article_title , 
( 
  (CASE WHEN A.article_title LIKE '%earn%' THEN 1 ELSE 0 END ) 
+ ( CASE WHEN A.article_title LIKE '%facebook%' THEN 1 ELSE 0 END )) AS count 
FROM site_articles A
A.article_id HAVING count>0 ORDER BY count DESC