简体   繁体   English

当php变量包含mysql查询时,如何在mysql查询中使用php变量?

[英]How to use php variables in mysql query while php variable contains mysql query?

How can I implement something like this in mysql? 我如何在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);

You can put those 3 queries in to one query: 您可以将这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 )
         ";

Try this 尝试这个

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


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

you have two identical queries , you could just have one . 您有两个相同的查询,您可能只有一个。 and use IN , not BETWEEN. 并使用IN,而不是BETWEEN。

although your query doesn't mean anything; 尽管您的查询没有任何意义; you need "()" for subqueries to work. 您需要“()”才能使子查询正常工作。

$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";

u can use a subselection: 您可以使用子选择:

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

But be careful: The Subselection result must be an Integer. 但请注意:“子选择”结果必须为整数。

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

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