Mysql按计数器分组(有多少条件)
嗨,每个人
我想;
我想按object_id分组,看看在一个名为match_number的字段中有多少条件与object_id相匹配。
喜欢结果;
Object_id Eşleşme_sayısı
1 3
2 5
筛选表格;
表中的sql代码;
CREATE TABLE `object_answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) unsigned DEFAULT NULL,
`object_id` int(11) unsigned DEFAULT NULL,
`answer` int(2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `object_answers_question_id_foreign` (`question_id`),
KEY `object_answers_object_id_foreign` (`object_id`),
CONSTRAINT `object_answers_object_id_foreign` FOREIGN KEY (`object_id`) REFERENCES `object` (`id`) ON DELETE CASCADE,
CONSTRAINT `object_answers_question_id_foreign` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `object_answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) unsigned DEFAULT NULL,
`object_id` int(11) unsigned DEFAULT NULL,
`answer` int(2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `object_answers_question_id_foreign` (`question_id`),
KEY `object_answers_object_id_foreign` (`object_id`),
CONSTRAINT `object_answers_object_id_foreign` FOREIGN KEY (`object_id`) REFERENCES `object` (`id`) ON DELETE CASCADE,
CONSTRAINT `object_answers_question_id_foreign` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
答案 0 :(得分:0)
您可以使用MySQL在数字上下文中将布尔表达式转换为0
或1
的功能。因此,您可以间接求和布尔表达式。
SELECT obejct_id,
sum(question_id IN (1, 2, 3, 4, 5)
AND answer = 2) "Eşleşme_sayısı"
FROM object_answers
GROUP BY object_id;