1. 程式人生 > >一張表多個字段是另一張表的主鍵,關聯查詢語句

一張表多個字段是另一張表的主鍵,關聯查詢語句

left join phone where table 查詢語句 tab tin 主鍵 let

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;

一張表多個字段是另一張表的主鍵,關聯查詢語句