MySql SELECT COUNT ...不喜欢

时间:2012-09-23 12:24:00

标签: mysql sql select count sql-like

我有这个查询

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

这会计算出现在列(限制)中的“我们”等值的总数。此列由muultiselect复选框中的值以“不寻常”的方式填充:

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

我已声明状态不喜欢但现在......问题......它还计算“限制”列未填充的行(某些列表不使用此列)。伯爵错了。

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:1)

这个怎么样?

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

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

答案 1 :(得分:1)

不需要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 :(得分:0)

限制'空值或空值列将通过"限制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

答案 3 :(得分:0)

SELECT 
    COUNT(*) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted IS NOT NULL 

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

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