简体   繁体   中英

Performing a query on the basis of the results of another SQL query

I have two tables with the name of customers and installments.ie

Customer Table:
id | name |contact |address
1  | xyz  |33333333|abc
2  | xrz  |33322333|abcd

Installments Table:
id | customer_id |amount_paid |amount_left | date
1  | 1           |2000        |3000        | 13/05/2017
2  | 1           |2000        |1000        | 13/06/2017

Now, I want to fetch the latest installment row from installments table for every user, I can use that with the following query,

SELECT * FROM installments WHERE customer_id=1 ORDER BY `id` DESC LIMIT 1

Now, the issue is that I want to do it for all the customer ids. I tried sub query thing but that doesn't supports multiple rows. I tried to store all customer IDs in an array in PHP and used "IN" but because the number of customers is more than 3000, it takes too long and returns an error of execution time exceeded. Any kind of help or tip will be really appreciated. Thanks

SELECT
    Customers.CustomerId,
    Customers.Name,
    Customers.Contact,
    Customers.Address,

    Installments.InstallmentId,
    Installments.AmountPaid,
    Installments.AmountLeft,
    Installments.Date
FROM
    Customers
    INNER JOIN
    (
        SELECT
            MAX( InstallmentId ) AS MaxInstallmentId,
            CustomerId
        FROM
            Installments
        GROUP BY
            CustomerId
    ) AS LatestInstallments ON Customers.CustomerId = LatestInstallments.CustomerId
    INNER JOIN Installments ON LatestInstallments.MaxInstallmentId = Installments.InstallmentId

you can do something like this

SELECT c.*,I.* FROM Customer_Table c LEFT JOIN Installments_Table I ON c.id=I.customer_id ORDER BY c.id DESC LIMIT 1

If You wants to add limit of list then only set limit else leave limit part. Untill I got Your Question this will be help you. else your problem can be something else.

SELECT cust.*,inst_disp.* FROM Customer AS cust
LEFT  JOIN (
          SELECT MAX(id) AS in_id, customer_id 
            FROM installments 
          GROUP BY customer_id
       ) inst
    ON inst.customer_id  = cust.id
LEFT JOIN installments as inst_disp ON inst_disp.id = inst.in_id

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