【问题标题】:How to get data Mysql group by with condition counter如何使用条件计数器获取数据 Mysql 组
【发布时间】:2019-09-10 22:28:00
【问题描述】:

Mysql 按计数器分组(多少个条件)

大家好

我想;

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

我想按 object_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;

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅如何提问页面以帮助澄清此问题
  • 要发布表的内容(这在 SQL 问题中是一件好事)使用 INSERT INTO 语句但 no 图像。

标签: mysql conditional-statements counter


【解决方案1】:

您可以使用 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;

【讨论】:

    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2020-12-04
    • 2018-12-20
    • 2018-08-20
    相关资源
    最近更新 更多