【问题标题】:MySql SELECT COUNT ... NOT LIKEMySql SELECT COUNT ...不喜欢
【发布时间】:2012-09-15 03:56:33
【问题描述】:

我有这个问题

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

这会计算出现在列中的诸如“我们”之类的值的总数(受限)。此列以这种“不寻常”的方式由多选复选框中的值填充:

*us*ca*uk* 等

这很有效。没问题。

现在,我需要计算这个值(我们)没有出现在哪里。 我试图做到这一点,一个“经典”。

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

我已经声明了 NOT LIKE 声明,但现在...问题...它还计算未填充“受限”列的行(某些列表不使用此列)。而且计数是错误的。

有人可以帮忙吗?

【问题讨论】:

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

标签: mysql sql select count sql-like


【解决方案1】:

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

匹配“我们”:

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

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

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

【讨论】:

    【解决方案2】:

    这个怎么样?

    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%'
    

    这将过滤掉限制为空或空的行。

    【讨论】:

      【解决方案3】:

      “restricted”列上的空值或空值将传递“restricted NOT 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
      

      【讨论】:

      • 那么为什么要有 CASE 声明呢?它什么也没做。
      【解决方案4】:
      SELECT 
          COUNT(*) AS totalcount 
      FROM 
          reviews 
      WHERE 
          restricted IS NOT NULL 
      

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

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

      【讨论】:

        猜你喜欢
        • 2013-05-26
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2012-03-17
        • 2011-07-17
        • 2019-07-03
        • 2014-03-30
        相关资源
        最近更新 更多