如何使用提前加入MySQL查询

如何使用提前加入MySQL查询,mysql,sql,join,Mysql,Sql,Join,因此,我一直在为这个问题苦苦挣扎,试图找出使用JOIN获得每个行星“CertCount”答案的最佳方法。我知道它想按行星分组,但我不知道行星从哪里来。以下是问题和代码: 查找按行星分组的人员持有的证书数量。这应该有两列第一,“名字”将是至少有一个认证的行星的名字。第二列应该是“CertCount”,是来自该星球的人持有的证书数量,例如,如果Lee在“Viper”和“Mechanical”中获得认证,Kara在“Viper”中获得认证,并且他们都来自Caprica,那么Caprica的“CertC

因此,我一直在为这个问题苦苦挣扎,试图找出使用JOIN获得每个行星“CertCount”答案的最佳方法。我知道它想按行星分组,但我不知道行星从哪里来。以下是问题和代码:

查找按行星分组的人员持有的证书数量。这应该有两列第一,“名字”将是至少有一个认证的行星的名字。第二列应该是“CertCount”,是来自该星球的人持有的证书数量,例如,如果Lee在“Viper”和“Mechanical”中获得认证,Kara在“Viper”中获得认证,并且他们都来自Caprica,那么Caprica的“CertCount”应该是3:

CREATE TABLE `bsg_cert` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

CREATE TABLE `bsg_cert_people` (
  `cid` int(11) NOT NULL DEFAULT '0',
  `pid` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`cid`,`pid`),
  KEY `pid` (`pid`),
  CONSTRAINT `bsg_cert_people_ibfk_1` FOREIGN KEY (`cid`) REFERENCES     `bsg_cert` (`id`),
  CONSTRAINT `bsg_cert_people_ibfk_2` FOREIGN KEY (`pid`) REFERENCES     `bsg_people` (`id`)
) ENGINE=InnoDB

CREATE TABLE `bsg_people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) DEFAULT NULL,
  `homeworld` int(11) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `homeworld` (`homeworld`),
  CONSTRAINT `bsg_people_ibfk_1` FOREIGN KEY (`homeworld`) REFERENCES     `bsg_planets` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB

CREATE TABLE `bsg_planets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `population` bigint(20) DEFAULT NULL,
  `language` varchar(255) DEFAULT NULL,
  `capital` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB
因此,就目前而言,我有以下几点:

SELECT  bsg_planets.name ,
   COUNT(*) AS CertCount
FROM bsg_cert_people people_cert

我知道我丢失了一些代码,但我不确定从这里走到哪里,可以在正确的方向上使用一点提示。

您需要根据表的主键和外键加入表,然后按
进行分组

SELECT  ps.id, 
        ps.name ,
        COUNT(distinct *) AS CertCount
FROM bsg_cert_people cp
JOIN bsg_people pe ON cp.pid = pe.id
JOIN bsg_planets ps ON pe.homeworld = ps.id
GROUP BY ps.id, ps.name

您只需根据表的公共id在所有3个表之间进行内部联接,然后使用Planet id进行分组

以下查询应该可以工作:

SELECT ps.name ,
       count(cert.cid) AS CertCount
FROM bsg_cert_people cert
JOIN bsg_people people ON cert.pid = people.id
JOIN bsg_planets planet ON people.homeworld = planet.id
GROUP BY plsnet.id
having count(distinct *) > 0;
希望有帮助