2013-01-18 82 views
1

查詢:到`IN`添加條件查詢

SELECT * FROM #__content WHERE featured=1 and catid=$category_id or catid IN 
(SELECT id FROM #__categories WHERE parent_id=$category_id) 

Featured=1作品只有在這裏catid=$category_idcatid IN (SELECT id FROM #__categories WHERE parent_id=$category_id)開始輸出所有行,並且特徵= 1的位置在此處被忽略。如何增加featured=1條件到catid IN

所以基本上它看起來像這樣由現在:

$query = "SELECT * FROM #__content WHERE featured=1 and catid=$category_id"; 
$query2 = "SELECT * FROM #__content WHERE catid IN 
    (SELECT id FROM #__categories WHERE parent_id=$category_id)"; 
+1

你能舉一些例子你想要的輸出嗎? – Dipali

回答

0

您需要添加括號強制評估的,你需要的順序:

SELECT * FROM #__content WHERE catid=$category_id OR (featured=1 AND catid IN 
(SELECT id FROM #__categories WHERE parent_id=$category_id)) 

由於ANDOR更高的優先級,當(featured=1 and catid=$category_id)爲真或catid位於由子查詢指定的IN列表中時,沒有括號的表達式爲真。

+0

謝謝你。 'SELECT * FROM #__content WHERE catid = $ category_id或catid IN(SELECT id FROM #__categories WHERE parent_id = $ category_id)AND featured = 1'我這樣做,效果很好。 – user1876234

+0

@ user1876234啊,明白了。我看到你現在想要達到的目標 - 只有在'featured'設置爲'1'時才顯示與'IN'列表相匹配的內容 – dasblinkenlight

0

加入怎麼樣?

$query = "SELECT * FROM #__content WHERE featured=1 and catid=$category_id"; 
$query2 = " 
SELECT * FROM #__content as con 
LEFT JOIN #__categories as cat 
on con.cat_id =cat.category_id 
WHERE cat.parent_id=$category_id;"