slek
slek

Reputation: 309

Get the first instance of a row using MS Access

EDITED:

I have this query wherein I want to SELECT the first instance of a record from the table petTable.

SELECT id, 
    pet_ID, 
    FIRST(petName), 
    First(Description) 
FROM petTable 
GROUP BY pet_ID;

The problem is I have huge number of records and this query is too slow. I discovered that GROUP BY slows down the query. Do you have any idea that could make this query faster? or better, a query wherein I don't need to use GROUP BY?

Upvotes: 2

Views: 5832

Answers (2)

HansUp
HansUp

Reputation: 97101

"The problem is I have huge number of records and this query is too slow. I discovered that GROUP BY slows down the query. Do you have any idea that could make this query faster?"

And an index on pet_ID, then create and test this query:

SELECT pet_ID, Min(id) AS MinOfid
FROM petTable
GROUP BY pet_ID;

Once you have that query working, you can join it back to the original table --- then it will select only the original rows which match based on id and you can retrieve the other fields you want from those matching rows.

SELECT pt.id, pt.pet_ID, pt.petName, pt.Description
FROM
    petTable AS pt
    INNER JOIN
    ( 
        SELECT pet_ID, Min(id) AS MinOfid
        FROM petTable
        GROUP BY pet_ID
    ) AS sub
    ON pt.id = sub.MinOfid;

Upvotes: 2

PaulFrancis
PaulFrancis

Reputation: 5809

Your Query could change as,

SELECT ID, pet_ID, petName, Description
FROM petTable
WHERE ID IN 
(SELECT Min(ID) As MinID FROM petTable GROUP BY pet_ID);

Or use the TOP clause,

SELECT petTable.petID, petTable.petName, petTable.[description]
FROM petTable
WHERE petTable.ID IN
   (SELECT TOP 1 ID                            
   FROM petTable AS tmpTbl                              
   WHERE tmpTbl.petID = petTable.petID        
   ORDER BY tmpTbl.petID DESC) 
ORDER BY petTable.petID, petTable.petName, petTable.[description];

Upvotes: 0

Related Questions