编写多条 SQL 语句的更简洁方法

发布于 2024-10-24 11:46:13 字数 811 浏览 1 评论 0原文

我正在寻找一种更简洁的方式来编写这些 sql 语句。我基本上想从表1中提取数据并根据表2的结果对其进行排序。第二个sql语句基于第一个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; 

     }
}

I'm looking for a cleaner way to write these sql statements. I'm basically wanting to pull data from table 1 and sort it based on the results of table 2. The second sql statement is based on the condition of the first. I have tried join but did not have any success with it.

Here's what I have working at the moment:

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

     }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南薇 2024-10-31 11:46:13

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

SQL statements can be combined into a single one with inner join like this

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文