【发布时间】:2022-09-24 13:06:05
【问题描述】:
我有一个下面的表格图,主要由 4 个表格组成,我想检索 company_name 和 person_name,这是他们在同一家公司的职位(CEO 和所有者)。
- 公司表
- 人员表
- 职位表
- Company_people 表,使用外键组合以上三个表
这是我的 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 是他们的职位是同一家公司的(CEO 和 Owner),这是我到目前为止尝试过的:
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我的问题是,这种方式正确吗?
如果您知道另一种正确且比我的方式更好的正确方式,您能帮我吗?
-
我想知道你的结果有什么问题?不准确指的是什么?计数(*)还是?你所有的结果都是正确的!史蒂夫乔布斯是苹果公司的老板,其他人是正确的!
-
您能详细说明
I would like to retrive company_name, person_name that are thier position are (CEO and Owner) of the same company吗? -
@learning 想象一下,如果这张表有数百万条记录,那么这个答案是否总是正确的?
标签: mysql