如何在mysql查询中使用php变量而php变量包含mysql查询?

时间:2014-05-21 08:58:21

标签: php mysql subquery

我如何在mysql中实现这样的东西?

$query1 = "SELECT id FROM table WHERE username = 'John'";
$query2 = "SELECT id FROM table WHERE username= 'Parsa'";

$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";



$result = mysql_query($query) or die('Query faild'.mysql_error());
$myrecord = mysql_fetch_assoc($result);

4 个答案:

答案 0 :(得分:1)

您可以将这3个查询放入一个查询中:

$query = "SELECT * FROM table WHERE id 
          BETWEEN
           ( SELECT id FROM table WHERE firstname = 'John' GROUP BY id ) 
          AND
           ( SELECT id FROM table WHERE firstname = 'Parsa' GROUP BY id )
         ";

答案 1 :(得分:1)

试试这个

$query1 ="SELECT GROUP_CONCAT(id) FROM table WHERE firstname in('John','Parsa')";


$query = "SELECT * FROM table WHERE id IN ($query1)";

你有两个相同的查询,你可以只有一个。并使用IN,而不是BETWEEN。

答案 2 :(得分:-1)

虽然你的查询没有任何意义;你需要“()”才能使子查询起作用。

$query1 = "(SELECT id FROM table WHERE username = 'John')";
$query2 = "(SELECT id FROM table WHERE username= 'Parsa')";

$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";

答案 3 :(得分:-1)

你可以使用一个子选择:

SELECT * FROM table WHERE id BETWEEN ($query1) AND ($query2)

但要小心:Subselection结果必须是整数。