如何在此sql表中找到所有员工访问的位置?

时间:2019-05-30 05:25:33

标签: mysql

我有一个看起来像这样的sql表:

CREATE TABLE `location_visits` (
  `employee1_name` varchar(255) NOT NULL,
  `employee2_name` varchar(255) NOT NULL,
  `region_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee1_name`,`employee2_name`),
  CONSTRAINT `location_visits_fk1` FOREIGN KEY (`employee1_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `location_visits_fk2` FOREIGN KEY (`employee2_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
)

员工成对地一起去,就像一个伙伴系统。我想找到所有员工都曾去过的地区。

如果有帮助,我还有一张表格列出了我所有的员工:

CREATE TABLE `employees` (
  `employee_name` varchar(255) NOT NULL,
  PRIMARY KEY ('employee_name')
)

当然,所有这些表都装载有数据。因此,对于location_visits表有效的数据示例为(John, Chris, Maine), (John, Adam, New Hampshire), (Adam, Chris, Maine)。在这种情况下,所有员工Adam, Chris, John访问的位置为Maine

什么样的sql命令会为我做这件事?

2 个答案:

答案 0 :(得分:1)

您需要获取每个区域中所有不同雇员的计数,并获得雇员总数等于employee表中雇员总数的区域。您的查询应如下所示:

SELECT COUNT(employee1_name), region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM location_visits
UNION
SELECT DISTINCT employee2_name, region_name FROM location_visits))
GROUP BY region_name
HAVING COUNT(employee1_name) =
       (SELECT COUNT(DISTINCT employee_name) FROM employees);

希望这会有所帮助!

答案 1 :(得分:0)

尝试

SELECT employee1_name, employee2_name FROM location_visits WHERE region_name='Maine'