-2

我想做以下事情:

SELECT count(id) FROM table WHERE value BETWEEN 3 AND 40;

但它应该执行以下操作:

SELECT count(id) FROM table WHERE value IN(3, 4, 5, 6, 7, 8, 9, 10, 11, ..., 40);

它甚至应该为 3 到 40 之间的值打印零计数(id),但不是 value = x。我想检查一个值是否在一个序列中(1、2、3、4、...、50)。

有谁知道如何用mysql实现这一点?

谢谢。

4

4 回答 4

1

MySQL 没有递归功能,因此您只能使用 NUMBERS 表技巧 -

  1. 创建一个只包含递增数字的表 - 使用 auto_increment 很容易做到:

    DROP TABLE IF EXISTS `example`.`numbers`;
    CREATE TABLE  `example`.`numbers` (
      `id` int(10) unsigned NOT NULL auto_increment,
       PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
  2. 使用以下方法填充表:

    INSERT INTO NUMBERS
      (id)
    VALUES
      (NULL)
    

    ...根据需要获取尽可能多的值。

  3. 这将返回您想要查看计数的值列表:

    SELECT n.id
      FROM NUMBERS n
     WHERE n.id BETWEEN 3 AND (? - 1)
        OR n.id BETWEEN (? + 1) AND 40
    
  4. LEFT JOIN 到您现有的表上,以便能够查看 COUNT 为零的位置:

      SELECT x.id AS value,
             COALESCE(COUNT(y.id), 0) AS cnt
        FROM (SELECT n.id
                FROM NUMBERS n
               WHERE n.id BETWEEN 3 AND (? - 1)
                  OR n.id BETWEEN (? + 1) AND 40) x
    LEFT JOIN YOUR_TABLE yt ON yt.value = x.id
     GROUP BY x.id
    
于 2010-08-23T18:17:18.067 回答
0

这是您要查找的内容的猜测:

select c.Value,  count(t.Value) as Count
from (
    select 3 as Value
    union all select 4
    union all select 5 
    union all select 6 
    union all select 7 
    union all select 8 
    union all select 9 --add more as needed
) c
left outer join MyTable t on c.Value = t.Value
group by c.Value
于 2010-08-23T18:12:03.877 回答
0

假设我理解你的问题:

SELECT count(id) FROM table WHERE value >= 3 AND value <= 40 AND value != 'x'

编辑:我想我知道你的意思

SELECT COALESCE(count(id),0)  FROM table WHERE value BETWEEN 3 AND 40;
于 2010-08-23T18:09:06.183 回答
0

我认为你正在寻找的是这样的:

SELECT value, count(id) FROM table
WHERE value BETWEEN 3 AND 40
GROUP BY value

但这不会为您提供不存在的值的任何 count(id) = 0 行。

于 2013-06-03T23:43:31.627 回答