我有一个下表,主要由四个表组成,我想检索company_name和person_name,这是他们的位置(首席执行官和所有者)的同一家公司。
Table
使用外键
组合上述三个表

下面是我的Mysql表:
#
# Structure for table "companies"
#
DROP TABLE IF EXISTS `companies`;
CREATE TABLE `companies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
#
# Data for table "companies"
#
INSERT INTO `companies` VALUES (1,'Apple'),(2,'Microsoft'),(3,'Tesla'),(4,'SpaceX');
#
# Structure for table "company_person"
#
DROP TABLE IF EXISTS `company_person`;
CREATE TABLE `company_person` (
`cp_id` int(11) NOT NULL AUTO_INCREMENT,
`company_id` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`position_id` int(11) NOT NULL,
PRIMARY KEY (`cp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
#
# Data for table "company_person"
#
INSERT INTO `company_person` VALUES (1,1,13,1),(2,1,13,2),(3,2,12,2),(4,2,12,1),(5,4,11,2),(6,4,11,1),(7,3,11,1),(8,3,11,2),(9,1,14,3),(10,2,16,3),(11,3,17,4),(12,4,20,3),(13,4,17,3),(14,2,18,3),(15,3,18,2),(16,4,17,2),(17,4,17,4),(18,1,12,2),(19,3,12,2),(20,4,12,1);
#
# Structure for table "people"
#
DROP TABLE IF EXISTS `people`;
CREATE TABLE `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
#
# Data for table "people"
#
INSERT INTO `people` VALUES (11,'Elon Mask'),(12,'Bill Gates'),(13,'Steve Jobs'),(14,'Azad Omer'),(15,'Johney Deep'),(16,'Brad Pitt'),(17,'Jeff'),(18,'Zukerberg'),(19,'Will Smith'),(20,'Rapar');
#
# Structure for table "position"
#
DROP TABLE IF EXISTS `position`;
CREATE TABLE `position` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
#
# Data for table "position"
#
INSERT INTO `position` VALUES (1,'Owner'),(2,'CEO'),(3,'Stake Holder'),(4,'Third Party');现在,我想检索一下company_name,person_name,他们的职位都是同一家公司的(首席执行官和所有者),以下是我迄今为止尝试过的:
SELECT
com.name,
p.name,
COUNT(*)
FROM `company_person`
INNER JOIN companies com
ON com.id=company_id
INNER JOIN people p
ON p.id = person_id
WHERE position_id IN(1, 2) # 1=Owner, 2=CEO
GROUP BY company_id, person_id
HAVING COUNT(*) > 1;这给了我一个我认为不准确的结果:
| com | person | COUNT(*)
| --- | ------ | --------
| Apple | Steve Jobs | 2
| Microsoft | Bill Gates | 2
| Tesla | Elon Mask | 2
| SpaceX | Elon Mask | 2 我的问题是,这条路合适吗?
如果你知道另一种正确的方法,比我的方法更好的话,你能帮帮我吗?
发布于 2022-09-24 05:06:05
据我所知,你想要的是,有许多问题
您的主表有一个distinct.
这里有一个简单的解决方案来说明这个概念。
select distinct p1.person_id, p1.company_id, com.name company, p.name person
from company_person p1
inner join companies com
on com.id=p1.company_id
inner join people p
on p.id = p1.person_id
where p1.position_id = 1
and exists (select p2.position_id
from company_person p2
where p2.position_id = 2)我已经将I留在了那里,因为在您进行连接以获取名称之前,它有助于构建查询。您可以从选择中删除它们。
https://stackoverflow.com/questions/73811516
复制相似问题