Return row from subselect
I have this MySQL DB scheme:
users (id, login)
coins (userid, value, curr)
I need to write select which will return result: login and max coin he have and currency of this coin.
I've tryed something like that:
SELECT login,
(
SELECT value, curr
FROM coins
WHERE coins.userid = users.id
ORDER BY value DESC
LIMIT 1
) AS ROW(value, curr开发者_运维百科)
FROM users
Its not working... I'll recieve error, that "Operand should contain 1 column(s)". I expected it, but I dont know any way, how to make it.
So i guess: Is there any way to return multiple-column-single-line (row) from subquery to parent query?
(Yes, I can use two subqueries, but its not effective.)
Thanks for your time.
SELECT u.login, g.MaxVal, c.curr
FROM users u JOIN coins c ON u.id = c.userid
JOIN (
SELECT userid, MAX(`Value`) MaxVal
FROM coins
GROUP BY userid
) g ON c.userid = g.userid AND c.Value = g.MaxVal
In a case of ties, the above query will return all coins with the highest value, if you want to only select 1 of the coins, you can add a GROUP BY
to the outer query:
SELECT u.login, g.MaxVal, c.curr
FROM users u JOIN coins c ON u.id = c.userid
JOIN (
SELECT userid, MAX(`Value`) MaxVal
FROM coins
GROUP BY userid
) g ON c.userid = g.userid AND c.Value = g.MaxVal
GROUP BY c.userid
精彩评论