用于过滤多对多关系的SQL查询

时间:2015-12-15 04:51:47

标签: c# sql postgresql

我有这个表用于多对多的关系

USER
-----
Id


CASE
----
Id
Created

Users_Cases
------------
UserId
CaseId

你能帮我找出sql查询来获取在特定日期(2015年10月14日)之前创建案例的用户吗?谢谢,

编辑:如果用户有2个案例,第一个案例是在日期之前创建的,另一个案例是在日期之后创建的,则结果中不应包含该案例

User
User1
User2
User3

Case
Case1 - 9/14/2015
Case2 - 11/14/2015
Case3 - 12/14/2015
Case4 - 8/15/2015

Users_Cases
User1 - Case1
User1 - Case2
User2 - Case3
User3 - Case4

预期结果:仅限User3。 User1有一个案例<比起日期,还有另一个案例> =日期,因此user1不包含在结果中。

3 个答案:

答案 0 :(得分:1)

SELECT *
FROM "user" u
INNER JOIN "Users_Cases" uc ON u.id = uc.UserId
INNER JOIN "CASE" c ON uc.CaseId = c.id WHERE c.Created < '10/14/2015'

OR

SELECT *
FROM "user"
WHERE id IN (
        SELECT UserId
        FROM "Users_Cases" uc
        INNER JOIN "CASE" c ON uc.CaseId = c.id WHERE c.Created < '10/14/2015' )
        )

编辑:根据OP的评论

SELECT *
FROM "user"
WHERE id IN (
        SELECT uc.UserId
        FROM "case" c
        INNER JOIN "Users_Cases" uc ON uc.CaseId = c.id
        WHERE c.Created < '10/14/2015'
        )

答案 1 :(得分:1)

可能这应该有效,因为我认为您想要排除那些在指定日期之后创建案例的用户。

Select * from User as A
    inner join UserCases as B on A.ID = B.UserID
    inner join case as C on B.CaseID = C.ID
Where C.Created <= @GivenDate
    and A.ID not in (Select UserID from User_cases as D 
                inner join case as E on D.CaseID = E.ID
                Where E.Created >= @GivenDate
            )

如果您只想要一个ID,请使用group by子句。

Select A.ID from User as A
    inner join UserCases as B on A.ID = B.UserID
    inner join case as C on B.CaseID = C.ID
Where C.Created <= @GivenDate
    and A.ID not in (Select UserID from User_cases as D 
                inner join case as E on D.CaseID = E.ID
                Where E.Created >= @GivenDate
            )
 group by A.ID

答案 2 :(得分:0)

SELECT U.*
FROM `USER` AS U
WHERE EXISTS (SELECT 1 FROM `Users_Cases` AS UC 
          INNER JOIN `case` AS C ON UC.CaseId=C.`id`
          WHERE UC.UserId=U.`id` 
          AND C.`Created`<'2015-10-14'
)