我有4张桌子。用户,文章,Langs,LangList
文章表: ...,uid(Users.id),lang(Langs.id),...
LangList表: id,uid(Users.id),langid(Langs.id)
我想为指定用户选择所有这些文章(例如Users.id = 66),这些文章位于他选择的语言列表中。
如果我这样做:
function FindActiveLangs($lang){
$sql ="SELECT langid FROM LangList WHERE `uid`= '66' AND `active`='1';";
$rsd = mysql_query($sql);
$lang_string = " ( ".$lang."lang = '0' ";
while($row = mysql_fetch_array($rsd)){
$lang_string .= " OR ".$lang."lang = '".$row['langid']."' ";
}
$lang_string .= " ) ";
return $lang_string;
} //end of FindActiveLangs
$tables = " Articles ";
$lang_string = FindActiveLangs("Articles.");
$where1 = "WHERE ".$lang_string." ";
$sql = "select distinct Articles.id, title, descr, thumb, relDate,
Articles.alias, Articles.lang, author, source
from ".$tables.$where1." and Users";
我在0.01-0.03秒内取得了结果
第二种方式,我认为清洁代码更好:
$sql = "select distinct Articles.id, title, descr, thumb, relDate,
Articles.alias, Articles.lang, author, source
from Articles
where lang IN
(SELECT langid FROM LangList WHERE uid= '66' AND active='1')";
我在1.1-1.3秒内取得了结果
有没有办法执行此查询,第二种方式具有更好的性能? “IN”杀死速度
提前致谢...
答案 0 :(得分:1)
查看EXISTS而不是IN。表现要好得多。
select distinct Articles.id, title, descr, thumb, relDate, Articles.alias, Articles.lang, author, source
from Articles, TagsList
where
Articles.lang = 0 OR
EXISTS
(SELECT *
FROM LangList
WHERE uid= '66' AND active='1'
AND langid = Articles.lang)
编辑:第二次尝试(检查表现是否更好):
SELECT Articles.*
FROM Articles
INNER JOIN LangList
ON langid = Articles.lang
WHERE uid= '66' AND active='1'
UNION
SELECT Articles.*
FROM Articles
WHERE
Articles.lang=0
AND
NOT EXISTS
(
SELECT *
FROM LangList
WHERE uid= '66' AND active='1'
AND langid = Articles.lang
)