更清洁的方式来编写这个多SQL语句

时间:2011-03-22 16:04:00

标签: sql select join merge

我正在寻找一种更简洁的方法来编写这些sql语句。我基本上想要从表1中提取数据并根据表2的结果对其进行排序。第二个sql语句基于第一个的条件。我尝试过加入,但没有取得任何成功。

这就是我现在所做的工作:

    $sql= "SELECT * FROM yt_Business_RegInfo WHERE deleted = '0' ORDER BY companyName ASC";

    //Execute SQL statement
    if(!($result = mysql_query($sql)))
    die("Error in executing query");

    while ($row = mysql_fetch_array($result)) { 
    $busID = $row['id'];
    $companyName = $row["companyName"];
    $membershipID = $row['membershipID'];


    $sql2= "SELECT * FROM yt_Business_Membership WHERE id = '$membershipID' AND approved = 1";

    //Execute SQL statement
    if(!($result2 = mysql_query($sql2)))
    die("Error in executing query");
   //Retrieve values
   while ($row2 = mysql_fetch_array($result2)) { 

    echo $companyName; 

     }
}

1 个答案:

答案 0 :(得分:1)

SQL语句可以组合成一个内部连接,如此

SELECT * FROM yt_Business_RegInfo R
INNER JOIN yt_Business_Membership M
    ON R.membershipID = M.ID AND R.approved = 1
WHERE R.deleted = '0'
ORDER BY R.companyName ASC