简体   繁体   中英

MYSQL: greatest-n-per-group issue

Problem of greatest-n-per-group and my MySQL version cannot use the LIMIT & IN (error 1235), so I need to use this kind of query (see answer here: 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

Subquery (t2 table) executed for exact match (card Number) returns exactly 5 rows (in this example): all perfect.

My issue/request:

Joining the two tables I would to obtain 5 rows and not only one, with the different 5 rows with the dates.

Your join is working fine. The problem is your select statement:

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

The use of MIN() and MAX() turn this into an aggregation query that returns only one row. Try this:

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

Or add a group by clause if you want that.

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