使用mysql查询的结果进入新查询

时间:2018-08-10 01:59:32

标签: php mysql

我有这个mysql表。

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

使用此代码选择了chris和jan

$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中。

3 个答案:

答案 0 :(得分:1)

您可以使用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) . "')";

答案 1 :(得分:1)

您可以使用如下所示的数据库查询来排除chrisjan

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

答案 2 :(得分:1)

假设您不知道结果集的名称,则可以简单地(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)";

快乐编码!

相关问题