简体   繁体   中英

SELECT MIN value with GROUP BY and INNER JOIN?

I have a query pulling data from 4 different tables;

SELECT cd.name, tt.card_number, tt.deck_count, tcg.url, MIN(tcgp.marketPrice) as 'price'
FROM card_occurrences tt
INNER JOIN card_database cd ON tt.card_number = cd.id
INNER JOIN tcgplayer_cards tcg ON cd.name = tcg.name
INNER JOIN tcgplayer_set_prices tcgp ON tcgp.productId = tcg.productID
GROUP BY tt.card_number
ORDER BY tt.deck_count DESC LIMIT 100

However, the tcg.url is wrong and I know it's a result of using MIN(tcgp.marketPrice) with GROUP BY .

If I exclude the MIN and `GROUP BY then I get the ungrouped results like so: 在此处输入图片说明

However, when I do MIN with GROUP BY then I am correctly getting the lowest price but the URL is wrong. It's getting the first one found. 在此处输入图片说明

I think I need to use another JOIN statement (or maybe a subquery?) but I'm not entirely sure. Some prodding in the right direction is welcome!

If you're using MySQL v8+ (or MariaDB 10.2+), then I think you should try using ROW_NUMBER() . Consider this example:

SELECT cd.name, tt.card_number, tt.deck_count, tcg.url, tcgp.marketPrice as 'price',
       ROW_NUMBER() OVER (PARTITION BY cd.name, tt.card_number ORDER BY tcgp.marketPrice) rn
FROM card_occurrences tt
INNER JOIN card_database cd ON tt.card_number = cd.id
INNER JOIN tcgplayer_cards tcg ON cd.name = tcg.name
INNER JOIN tcgplayer_set_prices tcgp ON tcgp.productId = tcg.productID;

The ROW_NUMBER() OVER (PARTITION BY cd.name, tt.card_number ORDER BY tcgp.marketPrice) rn function is assigning row number to the row value based on tcgp.marketPrice ascending while retaining the corresponding column value for the row.

Demo fiddle

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