代码之家  ›  专栏  ›  技术社区  ›  DavidF

MySql选择计数。。。不喜欢

  •  2
  • DavidF  · 技术社区  · 13 年前

    我有这个疑问

    SELECT 
        COUNT(
                CASE 
                    WHEN restricted LIKE '%us%' THEN 2 
                    ELSE 1 
                END) AS totalcount 
    FROM 
        reviews 
    WHERE 
        restricted LIKE '%us%'
    

    这将计算列中出现的值(如“us”)的总数(受限制)。此列由多选复选框中的值以这种“不寻常”的方式填充:

    *美国、加拿大、英国等。

    这是有效的。没问题。

    现在,我需要计算一下这个值(us)没有出现在哪里。 我试着这样做,一个“经典”。

    SELECT 
        COUNT(
                CASE 
                    WHEN restricted NOT LIKE '%us%' THEN 2 
                    ELSE 1 
                END
        ) AS totalcount 
    FROM 
        reviews 
    WHERE 
        restricted NOT LIKE '%us%'
    

    我已经宣布国家不喜欢,但现在。。。问题。。。它还计算“restricted”列未填充的行(有些列表不使用此列)。计数是错误的。

    有人能帮忙吗?

    4 回复  |  直到 13 年前
        1
  •  1
  •   PeteGO    13 年前

    不需要CASE语句。您的WHERE子句意味着ELSE永远不会被命中。

    匹配“我们”:

    SELECT 
      COUNT(restricted) AS 'Count matching *us*' 
    FROM 
      reviews 
    WHERE 
      restricted IS NOT NULL 
      AND restricted LIKE '%us%'
    

    与“我们”不匹配(包括null):

    SELECT 
      COUNT(restricted) AS 'Count not matching *us*' 
    FROM 
      reviews 
    WHERE 
      restricted IS NULL 
      OR restricted NOT LIKE '%us%'
    
        2
  •  1
  •   Vikdor    13 年前

    这个怎么样?

    SELECT 
        COUNT(*) AS totalcount 
    FROM 
        reviews 
    WHERE 
        restricted IS NOT NULL 
    -- In case you expect restricted to contain spaces, the following line should be 
    -- LTRIM(RTRIM(restricted)) != ''
    AND restricted != '' 
    AND restricted NOT LIKE '%us%'
    

    这将过滤出restricted为null或为空的行。

        3
  •  0
  •   Habibillah    13 年前

    “restricted”列上的空值或null值将传递“restrictedNOT LIKE'%us%” “语句。请尝试更改为:

    SELECT 
        COUNT(
                CASE 
                    WHEN restricted NOT LIKE '%us%' THEN 2 
                    ELSE 1 
                END
        ) AS totalcount 
    FROM 
        reviews 
    WHERE 
        restricted NOT LIKE '%us%' 
        AND restricted != '' 
        AND restricted IS NOT NULL
    
        4
  •  0
  •   Rizier123    11 年前
    SELECT 
        COUNT(*) AS totalcount 
    FROM 
        reviews 
    WHERE 
        restricted IS NOT NULL 
    

    如果您希望限制包含空格,则以下行应为

    LTRIM(RTRIM(restricted)) != ''
    AND restricted != '' 
    AND restricted NOT LIKE '%us%'