我在mySQL中寻找一种方法,只选择在链接表中具有相应记录的记录。我可能会遭遇隧道视觉,或者遗漏一些简单的东西。
除了上述要求之外,我还有以下查询:
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;
这与我之前的问题有关,在这里:Select rows Having Count in linked table
虽然此链接线程中的答案当时对我有用,但我现在需要上面查询中的附加信息。有什么方法可以限制它,以便只有链接表PROPERTY_PHOTOS PP
中的记录(链接ON P.ID = PP.PROPERTY_ID
)
提前感谢任何输入。
答案 0 :(得分:4)
尝试使用INNER JOIN而不是LEFT JOIN。 根据{{3}}的SQL规范:
The INNER JOIN keyword return rows when there is at least one match in both tables.
对于INNER JOIN,这变为:
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).
答案 1 :(得分:4)
INNER JOIN
应该为您执行此操作:
INNER JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID
这只会返回两个表中匹配的记录。
答案 2 :(得分:3)
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;
答案 3 :(得分:3)
你需要一个“内部联接”。
答案 4 :(得分:1)
还有一个JOIN
,但不是LEFT
SELECT ...
FROM PROPERTIES P
...
INNER JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID
或只是
SELECT ...
FROM PROPERTIES P
...
JOIN PROPERTY_PHOTOS PP ON P.ID = PP.PROPERTY_ID
答案 5 :(得分:-1)
注意:此查询实际上并不包含照片表,但我会假设您将其作为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;