The question about SQL subqueries
I want to select tblProperty.ID only when this query returns greater than 0
SELECT
COUNT(tblProperty.ID) AS count
FROM
tblTenant AS tblTenant
INNER JOIN tblRentalUnit
ON tblTenant.UnitID = tblRentalUnit.ID
INNER JOIN tblProperty
ON tblTenant.PropertyID = tblProperty.ID
AND tblRentalUnit.PropertyID = tblProperty.ID
WHERE tblProperty.ID = x
Where x is equal to the parent tblProperty.ID it is looking at. I don't know what "x" is.
How can i do this?
Database Structure:
tblTenant:
ID
PropertyID <--foreign key to tblProperty
UnitID <--foreign key to tblRentalUnit
Other Data
tblProperty:
ID
Other Data
tblRentalUnit:
ID
PropertyID <--foreign key to tblProperty
Other Data
Explanation of Query:
The query only selects properties that have rental units where tenants live.
a source to share
SELECT
tblProperty.ID
FROM
tblTenant AS tblTenant
INNER JOIN tblRentalUnit AS tblRentalUnit
ON tblTenant.UnitID = tblRentalUnit.ID
INNER JOIN tblProperty AS tblProperty
ON tblTenant.PropertyID = tblProperty.ID
AND tblRentalUnit.PropertyID = tblProperty.ID
GROUP BY tblProperty.ID
HAVING COUNT(tblProperty.ID) > 1
Must work.
a source to share
Query: Select only properties that have rental units where tenants live.
SELECT
p.ID
FROM
tblProperty AS p
INNER JOIN tblRentalUnit AS u ON u.PropertyID = p.ID
INNER JOIN tblTenant AS t ON t.UnitID = u.ID
GROUP BY
p.ID
This should do it. The inner join allows you to explicitly not select any unreferenced entries, which means it only selects properties that have rental units that have tenants.
I'm not sure why your tblTenant
links are for tblProperty
. It looks like it wasn't necessary as the link seems to be coming from the property of the tenant-> rental unit->.
a source to share