如何通过条件计数器获取数据Mysql组

问题描述 投票:-1回答:1

Mysql group by counter(多少条件)

嗨,大家好

我想要;

  • question_id 1和答案2
  • question_id 2和答案2
  • question_id 3和回答2
  • question_id 4和回答2
  • question_id 5和回答2

我想按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 condition counter
1个回答
0
投票

您可以使用MySQL在数字上下文中将布尔表达式转换为01的能力。因此,您可以间接求和布尔表达式。

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;
© www.soinside.com 2019 - 2024. All rights reserved.