2011-07-23 47 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); 
相關問題