[英]use result of mysql query into a new query
I have this mysql table. 我有这个mysql表。
name | total
chris | 5
jan | 3
bob | 2
eric | 4
chris and jan were selected using this code 使用此代码选择了chris和jan
$query = " select * from table where name = '$given_name' ";
// &given_name = result from another query
I want to store the result of the query to a variable. 我想将查询的结果存储到一个变量。
while($row=mysql_fetch_assoc($query)){
$result = $row['name'];
} // i want to store both chris and jan to $result
Then i will use the result of the query to another query. 然后,我将查询的结果用于另一个查询。 I want to select the remaining names.
我想选择其余的名字。 Not the ones on the first query.
不是第一个查询。 I want chris and jan not to be selected with this query because it is stored in $result
我希望此查询不选择chris和jan,因为它存储在$ result中
select * from table where name != $result ;
But one name was just stored in $result. 但是一个名称只是存储在$ result中。 I want them both to be stored in $result.
我希望它们都存储在$ result中。
You could use FIND_IN_SET
to see if the names had been fetched before. 您可以使用
FIND_IN_SET
来查看名称是否之前已被获取。 Firstly you need to make $result
an array of all the names: 首先,您需要使
$result
包含所有名称的数组:
$result = array();
while ($row=mysql_fetch_assoc($query)) {
$result[] = $row['name'];
}
Then you can write your query to exclude the names in $result
: 然后,您可以编写查询以排除
$result
的名称:
$sql = "SELECT * FROM table WHERE NOT FIND_IN_SET(name, '" . implode(',', $result) . "')";
您可以使用如下所示的数据库查询来排除chris
和jan
:
select * from table where name NOT IN( $result );
Assuming that you do not know the names of the resultset you can simply (a) select the first two names from the resultset, (b) concatenate them in a string and finally (c) use "NOT IN" as your query parameter. 假设您不知道结果集的名称,则可以简单地(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)";
Happy Coding! 编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.