Вопрос

I have a table named call_charges it has following data in it. enter image description here

I need to get all un-paid payments whose payment retries is also unpaid.

i.e rows which has transaction_bid not null and is_paid 0, will return records with id 6 and 10. But id 6 has has a paid retry(id 12, with retry_id 6 and is_paid 1), so row with id 6 should not be there in the result.

I have tried with:

SELECT `call_charges`.* FROM `call_charges` LEFT JOIN `call_charges` AS 
`retries_call_charges` ON `retries_call_charges`.`retry_id` = `call_charges`.`id`
WHERE `call_charges`.`is_paid` = 0 AND (`call_charges`.`transaction_bid` IS NOT NULL 
AND `call_charges`.`retry_id` IS NULL)

But it returns both the rows with id 6 and 10.

Thanks in advance.

Это было полезно?

Решение

Here you go:

SELECT c1.id
FROM call_charges c1
LEFT JOIN call_charges c2
ON c1.id = c2.retry_id AND c2.is_paid = 1
WHERE c1.transaction_bid IS NOT NULL
AND c1.is_paid = 0
AND c2.id IS NULL
AND c1.retry_id IS NULL

Working Fiddle: http://sqlfiddle.com/#!2/29549/13

c2.id could be null because a LEFT JOIN has been used. When c1.id does not match c2.retry_id then c2.id will be NULL.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top