简体   繁体   中英

SQL - Use result of one query for second query

Let's say I have a table payments.

ID | Amount |    Date    | Reference
 1 |   10   | 2020-09-01 |  911

Then I have a table registered_payments.

ID | Amount |    Date    | Note      | Bank Reference
 1 |   10   | 2020-09-01 |  911aa    | 000001
 2 |   10   | 2020-09-05 |  123vv    | 000002
 3 |   10   | 2020-09-07 |  555ss    | 000003

And then we have table bank_payments.

ID | Amount |    Date    | Bank Reference | Bank ID
 1 |   10   | 2020-09-01 | 000001         | 44
 2 |   10   | 2020-09-05 | 000002         | 33
 3 |   10   | 2020-09-07 | 000003         | 22

Then I have a query:

WITH cte AS(
   SELECT amount, 
          date, 
          reference 
   FROM 
          payments 
   WHERE 
          ID = 1
)
SELECT
   *
FROM
   registered_payments
WHERE
   amount = (SELECT amount FROM tmp)
   AND date = (SELECT date FROM tmp)
   AND note ilike '%' || (SELECT amount FROM tmp) || '%';

I need to show result of this query(not a problem).

But Can I use Bank Reference from the result(always 1 record) in another query and search for the payment in bank_payments with it somehow?

I have only read rights. Cannot create any function or table. PSQL used.

Thank for any help.

If I follow you correctly, you can flatten the logic as simple joins:

select ...      -- enumerate the columns you want here
from payments p
inner join registered_payments rp 
    on  rp.amount = p.amount
    and rp.date = p.date
    and rp.note ilike '%' || p.reference || '%'
inner join bank_payments bp
    on  bp.amount = rp.amount
    and bp.date = rp.date
    and bp.bank_reference = rp.bank_reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM