我正在我的网站上构建一个搜索功能,我在查找SQL中的错误时遇到了一些麻烦。有四个SQL语句用于使用AND和OR关键字返回相同搜索的计数。第二组SQL语句返回AND的实际结果,OR搜索根据当前搜索的页码进行限制。
下面我将展示和计数和搜索的SQL函数。 其他两个SQL语句的代码完全相同,只使用OR代替AND。
function _and_count($words) {
require_once("include/conn.inc.php");
$arraysize = count($words);
$and_count_sql = "SELECT COUNT(DISTINCT tg_id)
FROM tg_keywords
WHERE tg_keyword=";
if ($arraysize > 1) {
foreach($words as $word){
$count = 1;
if ($count == 1){
$and_count_sql .= "'".$word."' AND ";
}
elseif ($count < $arraysize){
$and_count_sql .= "tg_keyword='".$word."' AND ";
}
else {
$and_count_sql .= "'".$word."'";
}
$count++;
}
} elseif ($words == 1) {
$and_count_sql .= "'".$words."'";
}
$and_count_result = mysql_query($and_count_sql)
or die(mysql_error());
return $and_count_result;
}
function _search_and($words, $startpos, $endpos) {
require_once("include/conn.inc.php");
$arraysize = count($words);
$search_and_sql = "SELECT DISTINCT tg_id COUNT(*) AS nb
FROM tg_keywords
LEFT JOIN tg_info
ON tg_info.tg_id=tg_keywords.tg_id
WHERE tg_keyword=";
if ($arraysize > 1){
foreach($words as $word) {
$count = 1;
if ($count == 1 && $count < $arraysize) {
$search_and_sql .= "'".$word."' AND ";
} elseif ($count == 1 && $count == $arraysize) {
$search_and_sql .= "'".$word."'";
} elseif ($count < $arraysize) {
$search_and_sql .= "tg_keyword='".$word."' AND ";
} elseif ($arraysize == $count) {
$search_and_sql .= "'".$word."'";
}
$count++;
}
} elseif ($arraysize == 1) {
$search_and_sql .= "'".$words."'";
} else {
$search_and_sql .= "''";
}
$search_and_sql .= "GROUP BY tg_id
ORDER BY nb DESC, tg_info.date_added ASC
LIMIT ".$endpos." OFFSET ".$startpos;
$search_and_result = mysql_query($search_and_sql, $link)
or die(mysql_error());
$and_array = mysql_fetch_array($search_and_result);
return $and_array;
}
任何建议都将不胜感激。 谢谢 阿奇
答案 0 :(得分:4)
$search_and_sql = "SELECT DISTINCT tg_id COUNT(*) AS nb
tg_id和Count之间缺少逗号。
显示生成的查询的好习惯,即。 echo $ search_and_sql;在mysql_query之前
答案 1 :(得分:1)
您在每次循环迭代开始时设置$count = 1
,然后测试$count == 1
,以便您的SQL最后可能有一个额外的AND。
答案 2 :(得分:0)
看起来$ count在foreach循环中始终为1,因此最终得到一个尾随AND
答案 3 :(得分:0)
这里没有错误吗?
SELECT DISTINCT tg_id COUNT(*) AS nb
tg_id和COUNT(*)
之间应该有一个“,”如果错误不是来自这里,您能否回复一下您的SQL查询并给我们结果?