MySQL INNER JOIN select only one row from second table

后端 未结 11 1009
不知归路
不知归路 2020-11-30 21:11

I have a users table and a payments table, for each user, those of which have payments, may have multiple associated payments in the payments

11条回答
  •  醉酒成梦
    2020-11-30 21:40

    There are two problems with your query:

    1. Every table and subquery needs a name, so you have to name the subquery INNER JOIN (SELECT ...) AS p ON ....
    2. The subquery as you have it only returns one row period, but you actually want one row for each user. For that you need one query to get the max date and then self-join back to get the whole row.

    Assuming there are no ties for payments.date, try:

        SELECT u.*, p.* 
        FROM (
            SELECT MAX(p.date) AS date, p.user_id 
            FROM payments AS p
            GROUP BY p.user_id
        ) AS latestP
        INNER JOIN users AS u ON latestP.user_id = u.id
        INNER JOIN payments AS p ON p.user_id = u.id AND p.date = latestP.date
        WHERE u.package = 1
    

提交回复
热议问题