使用2个外键查找不匹配的记录

时间:2018-03-09 22:11:03

标签: mysql join

我有两张桌子:

表公司

+----------+-------------+----+
| Id | MainId | Type   | Name | 
+----+--------+--------+------+
| 1  |        | NO     |      |
| 2  |    1   | Filial |      |
| 3  |        | NO     |      |
| 4  |    3   | Filiar |      |
+-------------+--------+------+

表员工

+------------------+-------+-------+
| Id | Name        | CompId| FilId |
+------------------+-------+-------+
| 333| Simon       | 1     |       |
| 444| John        | 1     | 2     |
| 555| Andrew      |       | 4     |
| 777| Dennis      | 11    |       |
| 888| John        | 3     | 10    |
+------------------+-------+-------+
  1. 如何让所有在公司表中列出的公司工作的员工? =至少有一行(CompId或FilId)链接到公司表

  2. 中的行
  3. 如何让所有不在公司表中列出的公司工作的员工? =公司表中不存在CompId或FilId列

  4. 我已尝试过该解决方案,但效果不佳...

    第一

    SELECT * FROM `Employees`  
    INNER JOIN `Companies` ON `Employees`.`FilId` = `Companies`.`Id` 
    OR `Employees`.`FilId` = `Companies`.`Id`
    

    SHOW CREATE TABLE table_name添加了结果 删除了未使用的列

    CREATE TABLE `Employees` (
     `Id` varchar(10) NOT NULL,
     `Name` varchar(255) NOT NULL
     `CompId` varchar(10) NOT NULL,
     `FilId` varchar(10) NOT NULL,
      PRIMARY KEY (`Id`),
      KEY `empl_to_comps` (`VuzId`),
      KEY `empl_to_fils` (`FilId`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    
    CREATE TABLE `Companies` (
     `Id` varchar(10) NOT NULL DEFAULT '',
     `MainId` varchar(10) DEFAULT '',
     `Type` varchar(255) NOT NULL,
     `Name` varchar(255) NOT NULL
     PRIMARY KEY (`Id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    

1 个答案:

答案 0 :(得分:1)

SELECT DISTINCT e.*
FROM Employees e
JOIN Companies c ON c.Id IN (e.CompId, FilId);

SELECT e.*
FROM Employees e
LEFT JOIN Companies c ON c.Id IN (e.CompId, FilId)
WHERE c.Id IS NULL;

更新

根据数据和索引,以下两个查询可能会更快。虽然冗长,但它们比JOIN查询更具表现力。

SELECT e.*
FROM Employees e
WHERE EXISTS (
        SELECT *
        FROM Companies c
        WHERE c.Id = e.CompId
   )
   OR EXISTS (
        SELECT *
        FROM Companies c
        WHERE c.Id = e.FilId
   );


SELECT e.*
FROM Employees e
WHERE NOT EXISTS (
      SELECT *
      FROM Companies c
      WHERE c.Id = e.CompId
  )
  AND NOT EXISTS (
      SELECT *
      FROM Companies c
      WHERE c.Id = e.FilId
  );