基于另一个SQL查询的结果执行查询

时间:2017-06-13 08:26:27

标签: php mysql sql web

我有两个名为customers和installments.i.e。

的表
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

现在,我想从每个用户的分期付款表中获取最新的分期付款行,我可以使用以下查询,

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

现在,问题是我想为所有客户ID做这件事。我试过了子查询的东西但是它不支持多行。我尝试将所有客户ID存储在PHP中的数组中并使用" IN"但是因为客户数量超过3000,所以需要的时间太长而且会返回超出执行时间的错误。 任何形式的帮助或提示将非常感激。感谢

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

你可以做这样的事情

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

如果您想添加列表限制,则只设置限制其他假限制部分。直到我得到你的问题,这将对你有所帮助。否则你的问题可能是别的。

答案 2 :(得分:0)

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