如何在SQL语句中检索单个数据?

时间:2013-12-02 06:27:26

标签: php mysql

我的数据库中有一张表。数据库的结构如下:

网络表

PhoneModel                              Status  
Cisco Catalyst 2960 8port               Available
Cisco Catalyst 2960 8port               Available
Cisco Catalyst 3750G POE24              Available
Cisco Catalyst 3750E POE-48             Available
Cisco Catalyst 3750E POE-48             Available

我想为此表创建电子邮件通知。例如,如果Cisco Catalyst 3750E POE-48小于3,则将向用户发送电子邮件。我已经尝试过这样的SQL语句,但是如果数据库包含两个可用项目,它会显示两个相同的项目。

SQL语句是这样的:

$sql = "SELECT PhoneModel, Status FROM network WHERE PhoneModel='Cisco Catalyst 2960   
8port' AND Status='Available'";
$result = mysql_query( $sql ) or die( 'Query failed.'.mysql_error() );

$sql2 = "SELECT PhoneModel, Status FROM network WHERE PhoneModel='Cisco Catalyst 3750G     
POE24' AND Status='Available'";
$result2 = mysql_query( $sql2 ) or die( 'Query failed.'.mysql_error() );

$to       = 'my@email.com';
$subject  = 'Notification of less on stock';
$message = 'Dear IT Infra,<br/><br />Listed below are the accessories currently less in  
stock. <br/>Please prepare to purchase a new one if necessary.';
$headers  = 'From: company.com' . "\r\n";

while($row = mysql_fetch_array($result)) {
    $PhoneModel = $row['PhoneModel'];
    $Available = $row['Available'];
}
if( $row['Available'] < 1 ){
$message .= "<div style='margin:30px 0;'>
            Item : $PhoneModel<br />
            Available: $Available<br /></div>";
}


while($row = mysql_fetch_array($result2)) {
    $PhoneModel = $row['PhoneModel'];
    $Available = $row['Available'];
 }
if( $row['Available'] < 3 ){
$message .= "<div style='margin:30px 0;'>
            Item : $PhoneModel<br />
            Available: $Available<br /></div>";
 }

对于上述编码,电子邮件应发送出去并仅包含“Cisco Catalyst 3750G POE24”,但电子邮件中也包含“Cisco Catalyst 3750G POE24”。我可以知道编码中缺少什么吗?

1 个答案:

答案 0 :(得分:0)

在MySQL中,您可以使用“限制”

将结果集限制为一行
SELECT PhoneModel, Status
FROM network WHERE PhoneModel='Cisco Catalyst 3750G POE24' AND Status='Available'
LIMIT 1

PS: 这是MySQL PDO和MySQLi API的链接,它们取代了mysql_query:

这是为什么原来的MySql API现已弃用的良好链接: