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;

posted on 2017-06-08 14:16  vofill-work  阅读(4748)  评论(0编辑  收藏  举报