如果所有记录都匹配,如何从连接中获取结果

时间:2016-03-22 08:07:57

标签: mysql

我在编写SQL查询时遇到问题。我有两个名为'loans''loan_emilists'

的表

loan table

loan_emitlist table

我想从第一张表中获取贷款ID,即贷款,其中loan.emilists表状态全部为1。

例如: -

Loan id = 1因为在第二个表中,即'loan_emilists'loor_id = 1,所有状态值都为1。

MySQL查询: -

  

SELECT DISTINCT(loans.id)FROM loans LEFT JOIN loan_emilists ON   loans.id = loan_emilists.loan_id WHERE loan_emilists.status = 1

但它给了我1和2贷款.id。

1 个答案:

答案 0 :(得分:2)

你可以使用not exists():

SELECT s.id FROM loans s
WHERE NOT EXISTS(select 1 from loan_emilists t
                 where s.id = t.loan_id 
                   and t.status = 0)

如果贷款中的每个id在loan_emilists中总是有一行,如果你不需要加入,然后使用not exists():

SELECT DISTINCT s.id FROM loans s
INNER JOIN loan_emilists s1
 ON(s1.loan_id = s.id and s1.status = 1)
WHERE NOT EXISTS(select 1 from loan_emilists t
                 where s.id = t.loan_id 
                   and t.status = 0)

也可以使用左连接:

SELECT DISTINCT s.id FROM loans s
INNER JOIN loan_emilists s1
 ON(s1.loan_id = s.id and s1.status = 1)
LEFT JOIN loan_emilists t
 ON(t.loan_id = s.id AND t.status = 0)
WHERE t.loan_id is null