一张表多个字段是另一张表的主键,关联查询语句

时间:2021-03-03 15:01:01

CREATE TABLE `User`
(
  `Id` BIGINT AUTO_INCREMENT NOT NULL,
  `Name` VARCHAR(10) NULL,
  `Phone` VARCHAR(100) NULL,
  `IsDeleted` TINYINT NULL,
  PRIMARY KEY (Id)
);

CREATE TABLE `Email`
(
  `Id` BIGINT AUTO_INCREMENT NOT NULL,
  `FjUserId` BIGINT NULL,
  `SjUserId` BIGINT NULL,
  `CsUserId` BIGINT NULL,
  `IsDeleted` TINYINT NULL,
  PRIMARY KEY (Id)
);

 

方案一:

SELECT e.*
    ,u1.`Name`
    ,u2.`Name`
    ,u3.`Name`
FROM(SELECT * FROM `EmailTest` WHERE `IsDeleted` = 0) e
LEFT JOIN (SELECT * FROM `UserTest` WHERE `IsDeleted` = 0) u1
    ON u1.`Id` = e.`FjUserId`
LEFT JOIN (SELECT * FROM `UserTest` WHERE `IsDeleted` = 0) u2
    ON u2.`Id` = e.`SjUserId`
LEFT JOIN (SELECT * FROM `UserTest` WHERE `IsDeleted` = 0) u3
    ON u3.`Id` = e.`CsUserId`;

方案二:

SELECT e.*
    ,( SELECT `Name` FROM `UserTest` WHERE e.`FjUserId` = `Id` AND `IsDeleted` = 0) AS `Name1`
    ,( SELECT `Name` FROM `UserTest` WHERE e.`SjUserId` = `Id` AND `IsDeleted` = 0) AS `Name2`
    ,( SELECT `Name` FROM `UserTest` WHERE e.`CsUserId` = `Id` AND `IsDeleted` = 0) AS `Name3`
FROM `EmailTest` e
WHERE `IsDeleted` = 0;