我有一个查询返回操作的信用票据(CN)和借记票据(DN),每个CN都附带两个或更多DN(由字段payment_plan_id
引用)。在分页时,例如我必须带10个操作,即10 CN及其DN,但是如果我将限制保留为10,它还将计算我必须在查询中返回的事务的借方通知单。因此,它只会带来2,3或4个操作,具体取决于信用票据附带的DN数量。
SELECT
value, installment, payment_plan_id, model,
creation_date, operation
FROM payment_plant
WHERE model != 'IMMEDIATE'
AND operation IN ('CN', 'DN')
AND creation_date BETWEEN '2017-06-12' AND '2017-07-12 23:59:59'
ORDER BY
model,
creation_date,
operation
LIMIT 10
OFFSET 1
删除某些字段的表格示例:
| id | payment_plan_id | value | installment | operation |
---------------------------------------------------------
| 1 | b3cdaede | 12 | 1 | NC |
| 2 | b3cdaede | 3.5 | 1 | ND |
| 3 | b3cdaede | 1.2 | 1 | ND |
| 4 | e1d7f051 | 36 | 1 | NC |
| 5 | e1d7f051 | 5.9 | 1 | ND |
| 6 | 00e6a0b4 | 15 | 1 | NC |
| 7 | 00e6a0b4 | 1 | 1 | ND |
| 8 | 00e6a0b4 | 3.6 | 1 | ND |
如何限制限制以便只考虑NC?
答案 0 :(得分:0)
好吧,您在上面提供的查询并不能远程执行您所描述的内容。假设你真的想要"最后10 CN及其DN"。您也不能解释CN和DN的共同字段,因此我假设字段为payment_plan_id
和installment
。鉴于此,您将如何获得它:
WITH last_10_cn AS (
SELECT
value, installment, payment_plan_id, model,
creation_date
FROM payment_plant
WHERE model != 'IMMEDIATE'
AND operation = 'CN'
AND creation_date BETWEEN '2017-06-12' AND '2017-07-12 23:59:59'
ORDER BY
model,
creation_date,
operation
LIMIT 10
OFFSET 1 )
SELECT last_10_cn.*,
dn.value as dn_value, dn.model as dn_model,
dn.creation_date as dn_creation_date
FROM last_10_cn JOIN payment_plant as dn
ON last_10_cn.payment_plan_id = dn.payment_plan_id
AND last_10_cn.installment = dn.installment
ORDER BY
last_10_cn.model,
last_10_cn.creation_date,
last_10_cn.operation
dn.creation_date;
根据实际的连接条件以及您希望如何对事物进行排序来调整上述内容。
顺便说一下,你的桌面结构在这里给你带来了麻烦。 DN应该是一个单独的表,带有CN的外键。我意识到大多数GL并不是这样做的,但GL模型早于关系数据库。