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

Posted vofill-work

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一张表多个字段是另一张表的主键,关联查询语句相关的知识,希望对你有一定的参考价值。

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;

以上是关于一张表多个字段是另一张表的主键,关联查询语句的主要内容,如果未能解决你的问题,请参考以下文章

hibernate一对一关联

如何用标准SQL语句给一张表中添加多个字段

主键和外键的作用

sql查询的一个字段是另一张表的数量,怎么把查询到的数量直接在下一个字段使用

转换一个字段中含有多个另外一张表的id | | 行转列

在oracle中怎么把一张表的数据插入到另一张表中