简体   繁体   中英

Select only records with linked records

I am seeking a way in mySQL to select only records that have corresponding records in a linked table. I am likely suffering tunnel vision, or otherwise missing something simple.

I have the following query which currently works besides this requirement above:

SELECT P.ID, P.NAME, P.SEO_NAME, CI.City, R.Region, C.Country
FROM PROPERTIES P 
LEFT JOIN Cities CI ON P.CITY_ID = CI.CityId
LEFT JOIN Regions R ON P.REGION_ID = R.RegionID
LEFT JOIN Countries C ON P.COUNTRY_ID = C.CountryId 
WHERE APPROVED = '1' AND REGION_ID = '5400' 
ORDER BY RAND() LIMIT 1;

This is related to a previous question of mine, here: Select rows Having Count in linked table

While the answer in this linked thread worked for me at the time, I now require the additional information in the query above. Is there any way I can limit it so that only records with records in the linked table PROPERTY_PHOTOS PP (which links ON P.ID = PP.PROPERTY_ID )

Thanks in advance for any input.

Try using INNER JOIN instead of LEFT JOIN. According to the SQL specifications for INNER JOIN :

The INNER JOIN keyword return rows when there is at least one match in both tables.

For the LEFT JOIN , this becomes:

The LEFT JOIN keyword returns all rows from the left table (table_name1), 
even if there are no matches in the right table (table_name2).

An INNER JOIN should do this for you:

INNER JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID

This will only return records where there is a match in both tables.

SELECT P.ID, P.NAME, P.SEO_NAME, CI.City, R.Region, C.Country
FROM PROPERTIES P 
LEFT JOIN Cities CI ON P.CITY_ID = CI.CityId
LEFT JOIN Regions R ON P.REGION_ID = R.RegionID
LEFT JOIN Countries C ON P.COUNTRY_ID = C.CountryId 
**INNER JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID**
WHERE APPROVED = '1' AND REGION_ID = '5400' 
ORDER BY RAND() LIMIT 1;

您将需要一个“ INNER JOIN”。

One more JOIN , but not LEFT

SELECT ...
FROM PROPERTIES P
...
INNER JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID

or just

SELECT ...
FROM PROPERTIES P
...
JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID

because they are the same .

Note: This query doesn't actually include a photos table, but I will assume you are joining it as PP

SELECT P.ID, P.NAME, P.SEO_NAME, CI.City, R.Region, C.Country
FROM PROPERTIES P 
LEFT JOIN Cities CI ON P.CITY_ID = CI.CityId
LEFT JOIN Regions R ON P.REGION_ID = R.RegionID
LEFT JOIN Countries C ON P.COUNTRY_ID = C.CountryId 
WHERE APPROVED = '1' AND REGION_ID = '5400' AND PP.PROPERTY_ID IS NOT NULL
ORDER BY RAND() LIMIT 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