我有带有表的数据库:
文档具有loanId
和documentTeplateId
作为外键。
每个贷款都有多个文档。
我想选择没有文档loanId
的每笔贷款(或teplateId 100
)。
目前,我对以下SQL感到困惑:
SELECT l.id as loanId, d.id as documentId, d.document_templateid as documentTeplateId
FROM loan as l
LEFT JOIN document as d ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId DESC
很明显,它会给我类似的信息。
但这不是我想要的。
有什么建议吗?
答案 0 :(得分:1)
SELECT l.id as loanId
FROM loan as l
LEFT JOIN document as d
ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId DESC
GROUP BY loanId
“ GROUP BY loanId”会将具有相同loanId的行分组为一行,从而删除重复项。您只能选择loan.id使其正常工作,因为您似乎表明这是您唯一需要的值,它非常适合您的情况。
答案 1 :(得分:1)
您只需要不同的贷款ID:
SELECT distinct l.id as loanid
FROM loan as l
LEFT JOIN document as d
ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId desc
答案 2 :(得分:0)
我认为您想要聚合和一个having`子句:
SELECT l.id as loanid
FROM loan l LEFT JOIN
document d
ON d.loanid = l.id
GROPU BY l.id
HAVING SUM( d.document_templateid = 100 ) = 0;
如果您只想考虑有单据的贷款,则不需要JOIN
:
SELECT d.loanid
FROM document d
GROPU BY d.loanid
HAVING SUM( d.document_templateid = 100 ) = 0;