码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-08 14:53:51      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:sel   多个   ble   csu   not   test   sde   prim   字段   

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;

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

标签:sel   多个   ble   csu   not   test   sde   prim   字段   

原文地址:http://www.cnblogs.com/vofill/p/6962542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!