I am trying to execute what I think is an easy SQL statement, but I am receiving an error when I try and use a subquery saying that more than one column is being returned, but I need more than one column to be returned.
I am just trying to show two columns, my user's name, and their current balance
Here is the SQL:
SELECT playid, username, balance FROM plays order by playid desc limit 25
Which returns:
Play ID Username Balance
593 ken -3497
592 cass -204
591 cass -184
590 cass -164
589 ken -517
580 ken -837
579 sam 250
545 cass -134
544 cass -114
Which is exactly what I want. A list of all my members, and their balances. Now I need to run a SUBQUERY on this query, to only select the balance with the highest Id (The most recent balance) Which would return a table like this:
Play ID Username Balance
593 ken -3497
592 cass -204
579 sam 250
The most recent balance is the only thing that I am concerned with. When I try and execute this second query, I get an error saying that I am trying to return multiple columns. (which I am of course)
Any help would be greatly appreciated.
EDIT: You've now mentioned this is for MySQL. Try this:
SELECT
p1.playid,
p1.username,
p1.balance
FROM
plays p1
JOIN
(
SELECT
MAX(playid) AS playid,
username
FROM
plays
GROUP BY
username
) p2
ON (p2.username = p1.username)
AND (p2.playid = p1.playid);
- This is probably what you are looking for. I assume you want the most recent balance by username based on the play id:
SELECT
playid,
username,
balance
FROM
(
SELECT
playid,
username,
balance,
ROW_NUMBER() OVER(PARTITION BY username ORDER BY playid DESC) AS seq
FROM
plays
) base
WHERE
seq = 1
This sequences the records by username, on playid descending, then returns the most recent record for each.
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.