简体   繁体   English

根据另一个SQL查询的结果执行查询

[英]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. 现在,问题是我想对所有客户ID都这样做。 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. 我试图将所有客户ID存储在PHP数组中,并使用“ IN”,但是由于客户数超过3000,因此花费的时间太长,并返回执行时间超出的错误。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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