如何在mysql中搜索记录来处理这种情况?

时间:2011-07-23 12:06:38

标签: mysql sql database

我正在开发一个PHP / MYSQL搜索模块,我必须根据许多不同的标准搜索表,我有11个表,我已经使用多个连接来创建一个单独的MySQL查询并基于我想要的WHERE子句要搜索特定记录,这里是我正在使用的MYSQL查询。

SELECT
prop.id,
prop.serial,
prop.title,
prop.rating,
prop.addDate,
prop.approve,
prop.status,
prop.user_id as userId,
user_det.email as email,
user_det.name as name,
prop.area_id as areaId,
area.name as areaName,
area.zipCode as zipCode,
area.city_id as cityId,
city.name as cityName,
city.state_id as stateId,
state.name as stateName,
state.country_id as countryId,
country.name as countryName,
prop.subCategory_id as subCategoryId,
subCat.name as subCategoryName,
subCat.category_id as categoryId,
cat.name as categoryName,
prop.transaction_id as transactionId,
trans.name as transactionName,
price.area as landArea,
price.price as priceSqFt,
price.total_price as totalPrice,
features.bedroom,
features.bathroom,
features.balcony,
features.furnished,
features.floorNum,
features.totalFloor
FROM properties prop 
LEFT JOIN user_details user_det ON (prop.user_id = user_det.user_id) 
LEFT JOIN areas area ON (prop.area_id = area.id) 
LEFT JOIN cities city ON (area.city_id = city.id) 
LEFT JOIN states state ON (city.state_id = state.id) 
LEFT JOIN countries country ON (state.country_id = country.id) 
LEFT JOIN subCategories subCat ON (prop.subCategory_id = subCat.id) 
LEFT JOIN categories cat ON (subCat.category_id = cat.id) 
LEFT JOIN transactions trans ON (prop.transaction_id = trans.id) 
LEFT JOIN prop_prices price ON (price.property_id = prop.id) 
LEFT JOIN prop_features features ON (features.property_id = prop.id)

虽然一切都运行良好,但我有一个情况,我有一个名为prop_amenities的表是这个表的内容。

enter image description here

如上表中有多个property_id,如果我使用JOINS查询它,那么大部分它会返回重复记录或单个记录省略其他记录,具体取决于我使用的JOIN类型。所以我想以这种方式处理它。

使用表prop_amenities仅处理不返回结果的条件。 例如,我正在搜索具有设施ID为1,5,9,17和24的属性,那么它应该检查prop_amenities表中是否存在所有记录,即1,5,9,17和24这个案例。并返回包含所有上述选定列的相应记录。

我对使用MySQL处理这种情况毫无头绪。我该怎么做?

谢谢..

1 个答案:

答案 0 :(得分:2)

你说“检查prop_amenities表格中是否所有记录 存在 ”,这是关键词。

SELECT ...
FROM properties AS prop
LEFT JOIN ...
WHERE EXISTS (SELECT 1 FROM prop_amenities AS pa WHERE pa.property_id = prop.property_id AND pa.amenity_id = 7);