2016-10-27 30 views
0

我有一個問題。我需要根據某些條件從數據庫檢索數據,但有些情況會失敗。我在下面解釋我的查詢。Mysql查詢不能根據條件檢索數據

select b.member_id as b_member_id, 
b.rest_name, 
b.city, 
b.proviance, 
b.postal, 
b.address, 
b.country, 
b.person, 
b.mobile, 
b.url, 
b.status, 
b.premium, 
b.image, 
b.business_phone_no, 
b.email, 
b.multiple_image, 
b.latitude, 
b.longitude, 
b.quadrant, 
d.member_id as d_member_id, 
d.day_id, 
d.cat_id, 
d.subcat_id, 
d.comment, 
d.city, 
d.special_images, 
c.cat_id, 
c.special, 
sub.subcat_id, 
sub.subcat_name, 
sub.status, 
sl.day_id, 
sl.member_id, 
sl.date_from, 
sl.date_to 
from db_restaurant_basic as b left join db_restaurant_detail as d on b.member_id=d.member_id 
left join db_category as c on d.cat_id=c.cat_id 
left join db_subcategory as sub on d.subcat_id=sub.subcat_id 
left join db_special_images as sl on d.day_id=sl.day_id 
where b.city='2' and d.day_id='4' and c.special='1' 
and (((sl.date_from IS NULL or sl.date_from='') and (sl.date_to IS NULL or sl.date_to='')) or(sl.date_from <='2016-10-27' and sl.date_to >= '2016-10-27')) 
and b.status=1 
and sub.status=1 group by d.subcat_id ORDER BY b_member_id DESC 

這裏我的問題是有些值也是來不符合條件。這裏b.city='2'但是也有一些值也只是city=0而已。在這裏,我需要的價值應根據適當的匹配。請幫幫我。

+0

您在'WHERE'子句中有'or'部分。這可能導致這種情況。閱讀布爾邏輯:AND具有比OR更高的優先級。 –

+1

@BartFriederichs:(((sl.date_from IS NULL or sl.date_from ='')and(sl.date_to IS NULL or sl.date_to =''))or(sl.date_from <='2016-10-27 '和sl.date_to> ='2016-10-27'))'。這個條件是在一個括號內,我需要這個。 – subhra

+0

1.城市字段的數據類型是什麼?它是數字嗎?如果是,則不要使用字符串進行比較。 2.你能否提供一些樣本輸出,哪裏的輸出不符合你的期望?這將幫助我們縮小事情可能出錯的地方。 – Shadow

回答

0

使用應答窗口的格式化選項...

WHERE b.city = 2 
    AND d.day_id = 4 -- NOTE THAT THIS IS AN INNER JOIN! 
    AND c.special = 1 -- AND SO IS THIS !! 
2

您選擇d.city - 從db_restaurant_basic表 - 但是,你設置條件爲b.city='2' - 在db_restaurant_detail表。

所以任何一個城市爲0的結果都會顯示從d/db_restaurant_detail表中的城市。

如果您需要對此進行過濾,則需要添加and d.city=2

您應該檢查您是否可以更規範化數據庫結構,以避免在不同的表中存在相同的數據。

0

由於您在選擇列表(b.city和d.city)中有兩次城市,我必須假設您提到的city='0'值實際上是d.city='0'。爲了確保還d.city爲「2」,你可以在where子句中添加一個附加條件或指定這樣

select ... from db_restaurant_basic as b left join db_restaurant_detail as d on d.member_id=d.member_id and b.city = d.city left join ...

,甚至這樣的連接,擺脫模糊

select ... from db_restaurant_basic as b left join db_restaurant_detail as d using(member_id, city) left join ...