简体   繁体   English

MySQL:查询另一个查询结果并返回两个结果?

[英]MySQL: Query on another query result and return both results?

I am using following 'php' and 'MySQL' code to list most recent topics from my database and to list related titles below each of those titles... 我正在使用以下'php'和'MySQL'代码来列出数据库中的最新主题并在每个标题下面列出相关标题...

// 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'];
    }


}

This works fine. 这很好。 But the problem is that it uses a MySQL queries within a loop. 但是问题在于它在循环中使用了MySQL查询。 (second query runs 20 times) I've read it is not a good programming practice because it uses server resources heavily. (第二个查询运行20次),我读过它不是一种好的编程习惯,因为它大量使用服务器资源。

So, is there a way to do this with just one query or two queries without having to run a query within a loop? 因此,是否有一种方法可以只对一个查询或两个查询执行此操作,而不必在循环中运行查询?

Thank you 谢谢

First off, STOP USING mysql_*() functions. 首先,停止使用mysql_*()函数。 They have been deprecated for years. 他们已经过时多年。

Second, once you start using a reasonable database interface like PDO or even just mysqli, you can do prepared queries. 其次,一旦开始使用合理的数据库接口(例如PDO甚至是mysqli),就可以进行准备好的查询。 The query can be prepared outside the loop, which will save resources and reduce the time taken. 可以在循环外部准备查询,这将节省资源并减少时间。

Third, it's possible this could be done with one query, but would need DB structure posted to be certain. 第三,这可能只需要一个查询即可完成,但需要确定数据库结构。

EDIT: here's some untested PDO code: 编辑:这是一些未经测试的PDO代码:

<?php
try {
    $db = new PDO("mysql:host=localhost;dbname=my_database", "user", "pass");
} catch(PDOException $e) {
    echo $e->getMessage();
    exit;
}

$result = $db->query("SELECT * FROM my_table ORDER BY id DESC LIMIT 20");
$result->setFetchMode(PDO::FETCH_ASSOC);

$stmt = $db->prepare("SELECT * MATCH (title) AGAINST (? IN NATURAL LANGUAGE MODE) AS score FROM my_table MATCH (title) AGAINST (? IN NATURAL LANGUAGE MODE) HAVING score > 10  ORDER BY score DESC");

while ($row = $result->fetch()) {
    echo "Main Topic: $row[title]";
    $params = array($row["title"], $row["title"]);
    $result2 = $stmt->execute($params);
    $result2->setFetchMode(PDO::FETCH_ASSOC);
    while ($row2 = $result2->fetch()) {
        echo  "<br>$row2[title]";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM