MYSQL:每组最大的问题

时间:2014-10-08 12:05:15

标签: php mysql greatest-n-per-group

问题greatest-n-per-group和我的MySQL版本无法使用LIMIT& IN(错误1235),所以我需要使用这种查询(请参阅答案:answer

SELECT
                t1.idMemberCard,
                DATE(MIN(transactions.dateTransaction)) AS first_transaction,
                DATE(MAX(transactions.dateTransaction)) AS last_transaction,
                t2.*
                FROM membersCard AS t1
                INNER JOIN transactions ON transactions.idMemberCard = t1.idMemberCard
                INNER JOIN
                (
                    SELECT
                        membersCard.idMemberCard,
                        membersCard.cardNumber,
                        membersCard.firstNameMemberCard,
                        membersCard.lastNameMemberCard,
                        transactions.dateTransaction
                    FROM membersCard
                    INNER JOIN transactions ON transactions.idMemberCard = membersCard.idMemberCard
                    WHERE membersCard.sexMemberCard = 'M'
                    AND membersCard.cardNumber = '1100101308655'
                    AND
                    DATE(transactions.dateTransaction) BETWEEN ('2013-12-28') AND ('2014-08-13')
                    LIMIT 100
                ) AS t2
                ON t1.idMemberCard = t2.idMemberCard

为完全匹配(卡号)执行的子查询(t2表)正好返回5行(在本例中):all perfect。

我的问题/请求:

加入这两个表我将获得5行而不仅仅是一行,不同的5行包含日期。

1 个答案:

答案 0 :(得分:0)

您的join工作正常。问题是你的select声明:

 SELECT t1.idMemberCard,
        DATE(MIN(transactions.dateTransaction)) AS first_transaction,
        DATE(MAX(transactions.dateTransaction)) AS last_transaction,
        t2.*

使用MIN()MAX()将此转换为仅返回一行的聚合查询。试试这个:

 SELECT t1.idMemberCard,
        DATE(transactions.dateTransaction) AS first_transaction,
        DATE(transactions.dateTransaction) AS last_transaction,
        t2.*

如果需要,可以添加group by子句。