Skip to content
Advertisement

Speeding Up Access 2016 Query

I have a query that contains amongst other things batsmanIDs and League names (extract below). I have put together another query to return all records where a batsman has played in each of two Leagues.

The query works but it is very, very slow.

There are 48,000 records returned in the first query but when I use that it runs instantly.

Can anyone suggest how to speed the new query up?

Thanks

Query:

SELECT *
FROM AddDateLeagueSeasontoScorecardBatting
WHERE League ="Indian Premier League" AND batsmanId IN (SELECT batsmanId FROM AddDateLeagueSeasontoScorecardBatting WHERE League ="Big Bash League") OR League ="Big Bash League" AND batsmanId IN (SELECT batsmanId FROM AddDateLeagueSeasontoScorecardBatting WHERE League ="Indian Premier League");

Table: enter image description here

Advertisement

Answer

You could accomplish this using inner joins such that the query will return only those records with a batmans appearing in both subqueries:

select t1.* from 
(
    AddDateLeagueSeasontoScorecardBatting t1 inner join
    (
        select distinct batsmanid 
        from AddDateLeagueSeasontoScorecardBatting 
        where League ="Indian Premier League"
    ) t2 on t1.batsmanid = t2.batsmanid
) 
inner join
(
    select distinct batsmanid 
    from AddDateLeagueSeasontoScorecardBatting 
    where League ="Big Bash League"
) t3 on t1.batsmanid = t3.batsmanid

EDIT: To select batsmen who have only played in the two leagues in question (and no others), you might try:

select t1.* from 
AddDateLeagueSeasontoScorecardBatting t1 inner join
(
    select batsmanid
    from AddDateLeagueSeasontoScorecardBatting 
    group by batsmanid
    having 
        sum(League not in ("Indian Premier League", "Big Bash League")) = 0 and
        sum(League = "Indian Premier League") < 0 and 
        sum(League = "Big Bash League") < 0
) t2 on t1.batsmanid = t2.batsmanid
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement