SQL选择属于同一对象的用户

时间:2015-09-07 05:08:50

标签: mysql sql database select

我有一个MySQL数据库,我有一个User,Project和ProjectUser表。 ProjectUser表具有UserID和ProjectID,并将用户映射到项目。我希望能够查询两个不同用户的共同项目。因此,如果Bob属于项目A,B,C,D和Joe属于项目C,D,E,F ...那么当我知道Bob和Joe的UserID时,我想要选择项目C和D的信息。

2 个答案:

答案 0 :(得分:1)

假设这是您提供的元数据和示例。

create table User        (UserID    int, Name varchar(200));
create table Project     (ProjectID int, Name varchar(200), Information varchar(200));
create table ProjectUser (UserID    int, ProjectID int    );

INSERT INTO User        VALUE (1,'Bob'),(2,'Joe');
INSERT INTO Project     VALUE (1,'A','First'),(2,'B','Second'),(3,'C','Third'),(4,'D','Fourth'),(5,'E','Fifth'),(6,'F','Sixth');
INSERT INTO ProjectUser VALUE (1,1),(1,2),(1,3),(1,4),(2,3),(2,4),(2,5),(2,6);

假设 ProjectUser 表中的记录由 UserID ProjectID 唯一,您可以获取Bob和Joe分享的项目的详细信息:

SELECT Project.* FROM Project WHERE Project.ProjectID IN
(
   SELECT Project.ProjectID 

   FROM ProjectUser 

   INNER JOIN User
   ON User.UserID       = ProjectUser.UserID

   INNER JOIN Project
   ON Project.ProjectID = ProjectUser.ProjectID

   WHERE User.Name IN ('Bob','Joe')

   GROUP BY Project.ProjectID 

   HAVING COUNT(*) > 1
)

http://sqlfiddle.com/

上试用

答案 1 :(得分:0)

你可以分别为userId1和userId2选择项目,最后通过交叉它们你会发现有这两个用户的项目! 对于SQL服务器

select * from projects where PID IN
(select PID from ProjectUser PU1 where UserId = UserID1 
INTERSECT 
select PID from ProjectUser PU2 where UserId = UserID2)

并为mySql编写如下:

select * from projects where PID IN
    (select PID from ProjectUser PU1 where UserId = UserID1 and  
            PID In (select PID from ProjectUser PU2 where UserId = UserID2))