选择没有外键或没有足够外键的主键

时间:2017-09-26 21:43:17

标签: sql sqlite join

我希望获得所有没有外键或没有足够数量的费用ID,如确认_to_supply

例如,

Charge Table:
 id
 confirmation_to_supply

Pay Table:
 id
 charge_id

让我们放一些价值

Charge Table:
 id: 1  confirmation_to_supply: 1
 id: 2  confirmation_to_supply: 2
 id: 3  confirmation_to_supply: 3

Pay Table:
 id: 1 charge_id: 2
 id: 2 charge_id: 2
 id: 3 charge_id: 3

结果应该是

charge_id
-----------
    1
    3

因此在支付表中没有这样的外键,所以应该出现1 因为没有足够的外键作为charge_to_supply在费用表中,所以应该出现3。

我的问题与此问题非常相似:Selecting primary keys that do not have foreign keys in another table

 select char.id
 from Charge AS char
 left outer join Pay AS p on p.charge_id = char.id
 where p.charge_id is null 

此查询仅提供null

  charge_id
-----------
    1

我还需要获得身份证。

感谢' S

2 个答案:

答案 0 :(得分:0)

您可以使用group by和having子句执行此操作:

select char.id
from Charge AS char
left outer join Pay AS p on p.charge_id = char.id
group by char.id, char.confirmation_to_supply
having count(p.charge_id) < confirmation_to_supply

答案 1 :(得分:0)

如果您在WHERE语句中添加了一个OR,该语句显示了外键数小于2的键。

select char.id
 from Charge AS char
 left outer join Pay AS p on p.charge_id = char.id
 where p.charge_id is null OR (SELECT COUNT(p.charge_id) FROM Pay) < 2