我有这样的查询结果 http://i.imgur.com/9m7P3mX.png
修改: 这是实际的表格 http://pastebin.com/TZCGHKdt
第二次编辑: http://sqlfiddle.com/#!2/49bae/1
如果你在SQLFIDDLE链接中看到结果,它会在ID列中显示重复的条目。例如,ID列中的值26总共有4个值,查询显示它们分为3和1.我希望它们加入。
这是我正在使用的表的插入查询
INSERT INTO `capture_captive` (`capture_id_1`, `capture_id_2`, `capture_id_3`, `capture_id_4`, `capture_id_5`)
VALUES
(23, 32, 0, 0, 0),
(26, 25, 24, 0, 15),
(26, 32, 0, 0, 0),
(0, 0, 0, 0, 0),
(26, 26, 0, 0, 0),
(32, 32, 0, 0, 0);
我正在使用的查询是
select id, num from
(select `capture_id_1` id, (COUNT(capture_id_1)) num from capture_captive where capture_id_1<>0 group by capture_id_1
UNION
select `capture_id_2`, (COUNT(capture_id_2)) num from capture_captive where capture_id_2<>0 group by capture_id_2
UNION
select `capture_id_3`, (COUNT(capture_id_3)) num from capture_captive where capture_id_3<>0 group by capture_id_3
UNION
select `capture_id_4`, (COUNT(capture_id_4)) num from capture_captive where capture_id_4<>0 group by capture_id_4
UNION
select `capture_id_5`, (COUNT(capture_id_5)) num from capture_captive where capture_id_5<>0 group by capture_id_5 ) as E
where id<>0
order by id;
我想显示id的总数,与他们的ID有关。
提前致谢。
答案 0 :(得分:1)
有人可能会说这应该是评论,但是......
这里的主要问题不在于查询本身。您遇到normalization问题。当你发现自己时,这个问题会导致次优查询。
您应该明确考虑重新分解数据表。这是一个可能的“等效”(见http://sqlfiddle.com/#!2/759b9/2):
CREATE TABLE `capture_captive_norm` (`capture_group` int not null,
`capture_id` int not null,
`value` int,
PRIMARY KEY (`capture_group`, `capture_id`));
INSERT INTO `capture_captive_norm` (`capture_group`, `capture_id`, `value`)
VALUES
(1,1,23), (1,2,32), (1,3,0), (1,4,0), (1,5,0),
(2,1,26), (2,2,25), (2,3,24), (2,4,0), (2,5,15),
(3,1,26), (3,2,32), (3,3,0), (3,4,0), (3,5,0),
(4,1,0), (4,2,0), (4,3,0), (4,4,0), (4,5,0),
(5,1,26), (5,2,26), (5,3,0), (5,4,0), (5,5,0),
(6,1,32), (6,2,32), (6,3,0), (6,4,0), (6,5,0);
我同意看起来更复杂。但是:
我想显示id的总数,与他们的ID有关。
现在简单地说:
SELECT `capture_id`, COUNT(IF(`value` <> 0, 1, NULL))
FROM `capture_captive_norm`
GROUP BY `capture_id`;
产:
+-------------+----------------------------------+
| CAPTURE_ID | COUNT(IF(`VALUE` <> 0, 1, NULL)) |
+-------------+----------------------------------+
| 1 | 5 |
| 2 | 5 |
| 3 | 1 |
| 4 | 0 |
| 5 | 1 |
+-------------+----------------------------------+
根据您的理解,基于该示例,您现在可以轻松地查询该表,以按值计算捕获,或按ID 计算值。
请注意,通过使用特殊的NULL值来表示不存在的数据,这可能已缩短为:
SELECT `capture_id`, COUNT(`value`)
FROM `capture_captive_norm`
GROUP BY `capture_id`;
嗯......事实上,有了这个sheme,你不必为缺失的值插入 NULL。如果你只是“不插入它们”,当然COUNT()
将不会计算它们......
答案 1 :(得分:1)
答案 2 :(得分:1)
如果要保留原始表结构,以下查询应生成预期结果,与您建议的结果相比,需要的临时表和文件输出要少得多。请参阅http://sqlfiddle.com/#!2/49bae/4以比较它们(点击“查看执行计划”以查看查询执行计划):
SELECT `id`, COUNT(*)
FROM (
SELECT `capture_id_1` as `id` FROM `capture_captive`
UNION ALL SELECT `capture_id_2` FROM `capture_captive`
UNION ALL SELECT `capture_id_3` FROM `capture_captive`
UNION ALL SELECT `capture_id_4` FROM `capture_captive`
UNION ALL SELECT `capture_id_5` FROM `capture_captive`
) AS S
WHERE `id` <> 0
GROUP BY `id`
ORDER BY `id`