SQL结果添加

时间:2019-01-31 13:39:43

标签: mysql sql

我有带有表的数据库:

  • 贷款
  • 文档
  • DocumentTemplate

文档具有loanIddocumentTeplateId作为外键。

每个贷款都有多个文档

我想选择没有文档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

很明显,它会给我类似的信息。

enter image description here

但这不是我想要的。

有什么建议吗?

3 个答案:

答案 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;