我想做以下事情:
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);
它甚至应该打印出0到40之间的值的零计数(id),但不是值= x。我想检查一个值是否在序列中(1,2,3,4,...,50)。
有谁知道如何使用mysql实现这一目标?
感谢。
答案 0 :(得分:1)
MySQL没有递归功能,因此您只需使用NUMBERS表技巧 -
创建一个只保存递增数字的表 - 使用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;
使用以下方法填充表格:
INSERT INTO NUMBERS
(id)
VALUES
(NULL)
...根据需要提供尽可能多的价值。
这将返回您想要查看的值的列表:
SELECT n.id
FROM NUMBERS n
WHERE n.id BETWEEN 3 AND (? - 1)
OR n.id BETWEEN (? + 1) AND 40
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
答案 1 :(得分: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;
答案 2 :(得分: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
答案 3 :(得分:0)
我认为您正在寻找的是:
SELECT value, count(id) FROM table
WHERE value BETWEEN 3 AND 40
GROUP BY value
但是对于不存在的值,这不会给你任何计数(id)= 0行。