Mysql group by counter(多少条件)
嗨,大家好
我想要;
我想按group_id按组进行分组,并查看object_id与名为match_ number的字段中的条件数匹配的内容。
喜欢结果;
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;
您可以使用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;