Get the first instance of a row using MS Access

馋奶兔 提交于 2019-12-12 21:09:27

问题


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?


回答1:


"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;



回答2:


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];


来源:https://stackoverflow.com/questions/24952004/get-the-first-instance-of-a-row-using-ms-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!