2011-07-23 121 views
0

我正在开发一个PHP/MYSQL搜索模块,在那里我必须根据许多不同的标准搜索表,我有11个表,并且我已经使用多个连接来创建一个单一的MySQL查询,并基于WHERE子句,我打算搜索特定的记录,这里是我正在使用的MYSQL查询。我如何处理这种情况在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,如果我使用它,然后加入大部分将返回重复的记录或单个记录忽略别人取决于我使用的JOIN查询类型。所以我想这样处理它。

使用表prop_amenities只处理不返回结果的条件。 例如,我正在寻找一个有设施ID 1,5,9,17和24的房产,那么它应该检查所有记录是否存在于prop_amenities表中,即在这种情况下是1,5,9,17和24。并将所有上面选定的列返回相应的记录。

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

谢谢你..

回答

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); 
相关问题