我使用以下查询来搜索我的表。但它很慢,怎么能快速或改善呢?
if ($stit0 || $sabst0 || $saut0 || $saffl0){
$qt = "SELECT * FROM mytable WHERE (";
if ($stit0){ $qt.="(MATCH(title) AGAINST('$stit0' IN BOOLEAN MODE))"; }
if ($saut0){ $qt.=" AND (MATCH(authors) AGAINST('$saut0' IN BOOLEAN MODE)) "; }
if ($sabst0){ $qt.=" AND (MATCH(abstract) AGAINST('$sabst0' IN BOOLEAN MODE))"; }
if ($saffl0){ $qt.=" AND (MATCH(affiliation) AGAINST('$saffl0' IN BOOLEAN MODE))"; }
if ($_GET[filter]){ $qt.=" AND (pubtype='$_GET[filter]')"; }
$qt.=") ORDER BY year + pubdate DESC";
$qt = str_replace("WHERE ( AND", "WHERE (", $qt);
$qt1 = mysql_query($qt);
$nqs = mysql_num_rows($qt1);
}`
答案 0 :(得分:1)
您是否申报了全文索引?查询看起来很简单,因此未经索引的搜索可能会破坏您的数据库。
至于查询本身,我更喜欢用这种方式形成WHERE
子句,省去了很多麻烦。查询更具可读性。
// Define a list of constraints, put a default constraint on record types or whatever.
$conditions = array("someColumn = 1");
// Start collecting constraints based on already-sanitized user input
if ($someFilter) $conditions[] = "someInt = {$someFilter}";
if ($otherFilter) $conditions[] = "MATCH(textColumn) AGAINST('{$otherFilter}')";
// repeat as much as you like, the only drawback is you can't write complex logic here.
// now merge the constraints to form the where-clause
$conditions = implode(' AND ', $conditions);
// Query in heredoc is much cleaner and structured.
$query = <<<HEREDOC
SELECT * FROM yourTable
WHERE {$conditions}
ORDER BY year DESC, pubDate DESC
HEREDOC;
while ($result = mysql_fetch_assoc($query)) {
// do your stuff
}