1

我有一个疑问。我可以在一个查询中执行以下两个查询吗?

SELECT id FROM table1 WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) AND status<>200 ORDER BY time_stamp ASC LIMIT 2 "

以及从第一个选择查询中获取的 idSELECT email FROM table2 WHERE wid='".$xy."'" 在哪里。$xy

我的PHP代码:

$dat =mysql_query("SELECT * FROM table1 WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) AND status<>200 ORDER BY  time_stamp ASC LIMIT 2 ");
while($dt=  mysql_fetch_assoc($dat)){
$add=  mysql_query("SELECT email FROM table2 WHERE wid='".$dt['id']."'");
$result=  mysql_fetch_assoc($add);
$to=$result['email'];
$subject="site down";
$message="your site is down";
$header="From:admin@gmail.com";
$retval=mail($to,$subject,$message,$header);}

我的表格如下所示:

表格1:

id        url      status      time_stamp

9       dgfgg     404        2012:09:05 13:04:56

10       gfh      404        0000:00:00 00:00:00

11        fg      200        0000:00:00 00:00:00

表2:

wid    email

9       ufff@hguh

10      yfyff@hfg

11      yfyf@hg.com

任何人都可以建议一个可以完成工作的查询,而不是像我在我的 php 代码中那样写两个吗?

4

2 回答 2

0

尝试这个

SELECT email FROM table2 WHERE wid IN (SELECT id FROM table1 
WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) 
AND status<>200 ORDER BY time_stamp ASC LIMIT 2) 
于 2013-09-06T09:25:20.610 回答
-1
SELECT email FROM table2 WHERE wid=(SELECT id FROM table1 
WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) 
AND status<>200 ORDER BY time_stamp ASC LIMIT 2) 

糟糕,如果它返回多个 id 使用 IN 而不是 =

$dat =mysql_query("SELECT email FROM table2 WHERE wid IN(SELECT id FROM table1 
WHERE time_stamp>=DATE_SUB(NOW(),INTERVAL 10 MINUTE) 
AND status<>200 ORDER BY time_stamp ASC)LIMIT 2  ");
while($result = mysql_fetch_assoc($dat)){
$to=$result['email'];
$subject="site down";
$message="your site is down";
$header="From:admin@gmail.com";
$retval=mail($to,$subject,$message,$header);}

是的,从 PHP 5.5 开始不推荐使用 mysql 函数,请使用 mysqli 或 PDO。

编辑好,尝试将 LIMIT 2 放在第一个括号之外

http://sqlfiddle.com/#!2/1152d/1

于 2013-09-06T09:22:04.380 回答