查找未记录某些ID的记录

时间:2016-03-29 13:37:11

标签: mysql

我有两个表使用debt_id及其状态。如何获得无偿债务ID? 用不同的,存在的等尝试各种查询,但没有运气.. 也许有人有想法让我走上正轨:)

下表中的结果应为debt_id = 11(当债务未支付时)

+----+---------+---------------+
| PK | debt_id | debt_state_id |
+----+---------+---------------+
|  1 |       3 |             1 |
|  2 |       3 |             2 |
|  3 |      11 |             1 |
|  4 |      15 |             1 |
|  5 |      15 |             2 |
+----+---------+---------------+
+---------------+----------+
| debt_state_id |  status  |
+---------------+----------+
|             1 | not paid |
|             2 | paid     |
+---------------+----------+

1 个答案:

答案 0 :(得分:0)

您可以使用not exists

select t1.debt_id from table_name t1
where t1.debt_state_id = 1
and not exists (
 select 1 from table_name t2 
 where t1.debt_id = t2.debt_id
 and t2.debt_state_id = 2
)

此处table_name是问题的第一个表格