简体   繁体   中英

Order by desc and group by on cross table query

I've tried a few options I've seen for getting GROUP BY and ORDER BY to work together...but I can't get the right results.

feeding_types table
    id                          
    type                            
    quantity                                            
    feeding_id

feedings table
    id                                                      
    data_entry_id

The basic part of the query returns the following:

        id      type        feeding_id
        15236   dried_comm  13499
        15237   dried_comm  13500
        15286   dried_comm  13543
        15287   dried_comm  13544
        15294   tinned_comm 13550
        15295   dried_comm  13551
        15296   dried_comm  13552

What I want to do is use GROUP BY to get the latest dried_comm and tinned_comm records from these results, and filter out the rest.

I've tried this:

SELECT ft . * , MAX( ft.id ) ID
FROM feeding_types ft
INNER JOIN feeding_types ft2 ON ft2.id = ft.ID
JOIN feedings f1 ON ft.feeding_id = f1.id
WHERE f1.data_entry_id = 15758
GROUP BY ft.type
ORDER BY ID DESC

which results in:

id      type       feeding_id   ID 
15236   dried_comm  13499   15296
15294   tinned_comm 13550   15294

EDIT: the expected results would be id type feeding_id ID 15296 dried_comm 13552 15296 15294 tinned_comm 13550 15294

Any ideas how to get this working correctly?

The underlying logic does not match very well your actual algorithm. Let me suggest the following instead:

SELECT ft.*
FROM feeding_types ft
    JOIN (
        SELECT type, MAX(id) AS id 
        FROM feeding_types 
        GROUP BY type
    ) t ON t.type = ft.type AND t.id = ft.id
    JOIN feedings f1 ON ft.feeding_id = f1.id AND f1.data_entry_id = 15758

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