在查询中将条件添加到“IN”

时间:2013-01-18 11:15:36

标签: mysql

查询:

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_id。在此处忽略启动此catid 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 )";

2 个答案:

答案 0 :(得分:0)

您需要添加括号以强制执行所需的评估顺序:

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

由于AND的优先级高于OR,因此当(featured=1 and catid=$category_id)为真,或者catid列在IN列表中时,没有括号的表达式为真由子查询指定。

答案 1 :(得分: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;"