将mysql查询的结果用于新查询

o4tp2gmn  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(254)

我有这张table。

name    |     total
chris   |     5
jan     |     3
bob     |     2
eric    |     4

克里斯和简是用这个代码选出来的

$query =  " select * from table where name = '$given_name' "; 
// &given_name = result from another query

我想将查询结果存储到一个变量中。

while($row=mysql_fetch_assoc($query)){
    $result = $row['name']; 
} // i want to store both chris and jan to $result

然后我将使用查询的结果进行另一个查询。我想选择剩下的名字。不是第一个查询中的。我不希望chris和jan被选中,因为它存储在$result中

select * from table where name != $result ;

但$result中只存储了一个名称。我希望它们都存储在$result中。

o7jaxewo

o7jaxewo1#

你可以用 FIND_IN_SET 看看这些名字以前有没有被取过。首先你需要 $result 所有名称的数组:

$result = array();
while ($row=mysql_fetch_assoc($query)) {
     $result[] = $row['name']; 
}

然后可以编写查询以排除 $result :

$sql = "SELECT * FROM table WHERE NOT FIND_IN_SET(name, '" . implode(',', $result) . "')";
46scxncf

46scxncf2#

假设您不知道结果集的名称,您可以简单地(a)从结果集中选择前两个名称,(b)将它们串联在一个字符串中,最后(c)使用“not in”作为查询参数。

$numPicks = 2; // decide how many names you want in the list
// OR if you want to exclude ALL names found in the first query
$num_rows = mysql_num_rows($query);

$nameList = ''; // start with an empty string
for($i=0; $i<$numPicks; $i++) { // then use $num_rows here instead of numPicks
    $nameList .= $row['name'].',';
}
$nameList = rtrim($nameList,','); // remove trailing comma from the string

$sql = "select * from table where name NOT IN ($nameList)";

快乐的编码!

xu3bshqb

xu3bshqb3#

您可以使用下面的数据库查询来排除 chris 以及 jan :

select * from table where name NOT IN( $result );

相关问题