使用"至少一个"选择记录条件1:n外键关系

时间:2015-04-14 21:42:56

标签: sql sql-server tsql

我在SQL Server数据库中有三个表:SubmissionQuoteCompanySubmissionQuoteCompanyQuote的外键关系为1:n,即报价属于一个提交和一个公司。我有一个查询,为那些具有指定公司至少一个报价的提交选择所有报价:

SELECT *
FROM Submission S, Quote Q, Company C
WHERE Q.submissionId = S.submissionId AND
    Q.companyId = C.companyId AND
    EXISTS (
        SELECT *
        FROM Quote T
        WHERE T.submissionId = S.submissionId AND
            T.companyId = @companyId
    )
ORDER BY S.legalName

是否有更高效和/或更简洁的方式来完成我在这里所做的事情?我无法摆脱应有的感觉。

2 个答案:

答案 0 :(得分:2)

SELECT *
FROM Submission S
INNER JOIN Quote Q   ON Q.submissionId = S.submissionId
INNER JOIN Company C ON Q.companyId = C.companyId 
WHERE  Q.companyId = @companyId
ORDER BY S.legalName

修改

SELECT *
FROM Submission S
INNER JOIN Quote Q   ON Q.submissionId = S.submissionId
INNER JOIN Company C ON Q.companyId = C.companyId 
WHERE  EXISTS (SELECT 1 
               FROM Submission Sub
               INNER JOIN Quote Qt  ON Qt.submissionId = Sub.submissionId
               WHERE Sub.submissionId = S.submissionId
                AND  Qt.companyId = @companyId)
ORDER BY S.legalName

答案 1 :(得分:0)

加入子选择语句以获取特定的提交者。

SELECT * 
FROM Submission S 
INNER JOIN Quote Q 
        ON Q.submissionId = S.submissionId
INNER JOIN Company C 
        ON Q.companyId =C.companyId  
INNER JOIN (SELECT DISTINCT qt.submissionId 
            FROM Quote qt 
            WHERE qt.companyId = @companyId) Q2
        ON Q2.submissionId = S.submissionId
ORDER BY S.legalName