tags:

views:

214

answers:

3

I have a table that logs rows with some duplicate data.

The column fields are as follows:
id: primary key, auto inc.
member_id: int index
item_qt: int

id, member_id, item_qt, timestamp

553, 107, 10, time
552, 107, 25, time
551, 122, 6, time
550, 122, 9, time
549, 107, 19, time

I would like to do a few things:

How would you select the latest unique rows,
sum the item_qt,
join on a 'username' table. cols: id, name
and sort descending

Anyone have suggestions for a subselect query
without the high overhead of filesorting? Or possibly another reconfiguration of the data?

This is very similar: I just can't get the syntax correct.
http://stackoverflow.com/questions/1227619/retrieve-last-latest-distinct-highest-value

A: 

Not sure how all this fits together as I don't 100% understand what you are asking...

To get the last row in the table

select top 1 * from [table] order by id desc

To sum a colum

select sum(item_qt) as SumItem_qt from [table]

For joins just google "inner join"

Sort desc is just order by column name desc

Rippo
"SELEC TOP n" is a Microsoft SQL Server syntax. It's not supported by the SQL standard, or other brands of RDBMS (except for Sybase, which shares common code with MS SQL Server).
Bill Karwin
I noticed that also. Seemed sort of odd. Not really familiar with MS SQL. :)
rrrfusco
oops had my MS head on!remove TOP 1 and add LIMIT 1 at end of SQL statement
Rippo
A: 

Sorry for not being clear. If you refer to the db table row info i've given above:

I want to retrieve the latest rows per unique member id. Without joining on the username table, here is my very slow code for what I want to retrieve.

Something like:

SELECT * FROM table1
WHERE id IN
( SELECT max( id ) FROM table1 GROUP BY member_id )
ORDER BY id DESC LIMIT 5

To retrieve:
553, 107, 10, time
551, 122, 6, time

I also wanted to sum all(item_qt) for each member_id within the last 5 minutes in the same query. I think this may be more complicated...

rrrfusco
@rrrfusco: I updated my answer based on what you provided.
OMG Ponies
A: 

OK then use...

SELECT un.name, t.item_qt
FROM TABLE t
JOIN USERNAME un ON un.id = t.member_id
ORDER BY t.id DESC LIMIT 1;

You could also use say LIMIT 5 to get 5 records...

When you say slow what do you mean? There may appear to be a problem that we don't know about. I suspect there may be lots of records and no indexes....

It may be wise to post the schema of both tables so we can help you further.... Also give an indication of number of rows in each table....

Rippo
Hi Rippo. I appreciate the comments. Your SQL does not address a needed subquery and group by member_id, which I think is necessary. If you run an EXPLAIN on the SQL I posted Sep. 7 1:12, it runs fairly fast, but I am looking for a improved workaround, possibly with joins and union.Indexes and schema are in the inital post. Records will increase to thousands.
rrrfusco