MySQL:获取每个选定行的相关结果

时间:2014-02-19 10:46:44

标签: php mysql performance

我正在使用下面的基本选择查询来显示我表格中的最新20行。

SELECT * FROM my_table  ORDER BY id DESC limit 0,20

然后我想获得上面选择的每一行的相关结果......我正在做的是在'php'中查询循环中的每一行...

SELECT * MATCH (title)
AGAINST('$main_title'IN NATURAL LANGUAGE MODE)AS 
score FROM my_table  MATCH(title)  AGAINST('$main_title'IN NATURAL LANGUAGE MODE)
HAVING score > 10  ORDER BY score DESC

所以完整的'PHP'代码如下所示:

<?php
// First Query 
$query= mysql_query("SELECT * FROM my_table  ORDER BY id DESC limit 0,20");  
$result = mysql_query($query) 

while($row = mysql_fetch_array($result)){
echo "Main Topic: ".$row['title'];
$main_title = $row['title'];
    echo "Related to this Topic:";

   // Second Query 
    $related_query= mysql_query("
    SELECT * MATCH (title)
    AGAINST('$main_title'IN NATURAL LANGUAGE MODE)AS 
    score FROM my_table  MATCH(title)  AGAINST('$main_title'IN NATURAL LANGUAGE MODE)
    HAVING score > 10  ORDER BY score DESC
    ");  
    $related_result = mysql_query($related_query) 

            while($related_row = mysql_fetch_array($related_result)){
            echo  "<br>". $related_row['title'];
    }


}
?>

但我知道在循环中运行第二个查询的效率非常低,所以我想在主查询中获得这些“相关结果”(或者在单独的单个查询中,而不必在一个查询中运行它环)

基本上我正在寻找一种更有效率的方法......

我有办法做到这一点吗?

谢谢

2 个答案:

答案 0 :(得分:1)

假设您只想拥有标题和分数,这会有效吗?

SELECT MATCH(title) AGAINST('$main_title' IN NATURAL LANGUAGE MODE) as SCORE,
title FROM my_table WHERE  
MATCH(title) AGAINST('$main_title' IN NATURAL LANGUAGE MODE)
AND score > 10 AND id<=20 ORDER BY score DESC;

答案 1 :(得分:1)

首先,我认为第二个查询更像是这样:

SELECT mt.*,
       MATCH (title) AGAINST('$main_title'IN NATURAL LANGUAGE MODE) AS score
FROM my_table mt
WHERE MATCH(title) AGAINST('$main_title' IN NATURAL LANGUAGE MODE) > 10
ORDER BY score DESC;

如果您只想在my_table中为20个ID执行此操作,请使用子查询:

SELECT mt.*,
       MATCH (title) AGAINST('$main_title'IN NATURAL LANGUAGE MODE) AS score
FROM (select mt.*
      from my_table mt
      order by id desc
      limit 0, 20
     ) mt
WHERE MATCH(title) AGAINST('$main_title' IN NATURAL LANGUAGE MODE) > 10
ORDER BY score DESC;