简体   繁体   中英

Nesting SQL Statements to create Gridview with fields from several tables

I have a Search page where the user will select the Community Name and upon pressing the Search button, a Gridview will populate displaying the owner name, resident name, and address of all the accounts in that Community.

I have the following tables: Communities, Addresses, Owners, Residents. Addresses has a foreign key of CommunityID. Owners and Residents each have a foreign key of AddressID.

With the SQL statement

SELECT 
     Addresses.AddressID 
FROM 
     Addresses 
     INNER JOIN Communities ON Addresses.CommunityID = Communities.CommunityID 
WHERE 
     Addresses.CommunityID = '1'    

I get a proper list of appropriate AddressIDs that are from the first community. From there I want to list the owners, residents, and actual addresses that belong to each of these AddressIDs.

I feel like this should work:

SELECT        
     Owners.OwnLName, 
     Owners.OwnFName, 
     Residents.ResLName, 
     Residents.ResFName, 
     Addresses.Address
FROM            
     Addresses 
     INNER JOIN Owners ON Addresses.AddressID = Owners.AddressID 
     INNER JOIN Residents ON Owners.OwnerID = Residents.OwnerID 
WHERE 
     Owners.AddressID = ALL 
                        (
                           SELECT 
                               Addresses.AddressID 
                           FROM 
                               Addresses 
                               INNER JOIN Communities ON Addresses.CommunityID =Communities.CommunityID            
                               WHERE Addresses.CommunityID = '1'
                        )

I've messed around with this for so long and can't seem to wrap my mind around how to properly formulate this.

Any help would be greatly appreciated!!

You can do something like this.

SELECT        
     Owners.OwnLName, 
     Owners.OwnFName, 
     Residents.ResLName, 
     Residents.ResFName, 
     Addresses.Address
FROM            
     Addresses 
     INNER JOIN Owners ON Addresses.AddressID = Owners.AddressID 
     INNER JOIN Residents ON Owners.OwnerID = Residents.OwnerID 
WHERE 
     Owners.AddressID IN 
                        (
                           SELECT 
                               Addresses.AddressID 
                           FROM 
                               Addresses 
                               INNER JOIN Communities ON Addresses.CommunityID =Communities.CommunityID            
                           WHERE Addresses.CommunityID = '1'
                        ) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM