简体   繁体   English

MySQL结合了几个选择语句

[英]MySQL combining several select statements

Wondering how/if I can combine the two select statements. 想知道如何/是否可以合并两个选择语句。

        $searchCat = $mysqli->query("SELECT category_id, category.name FROM category WHERE category.name = '$searchTerm'");

    while ($r=$searchCat->fetch_assoc()) {
        $category_id=$r["category_id"];

        $searchBus = $mysqli->query("SELECT business.name, business.street FROM business WHERE business.category_id = '$category_id'");             

        while ($r=$searchBus->fetch_assoc()) {
            $name=$r["name"];
            $street=$r["street"];

            echo "$name, $street<br>";
        }
    } // end of while

For output I only need the data from the Business table, the 1st select finds the correlating ID of the searched term, that Id is also housed in the Business table. 对于输出,我只需要Business表中的数据,第一个选择将找到搜索词的相关ID,该ID也包含在Business表中。

So can I do a join or union where the 1st select gets the id and then it is passed to the 2nd Select allowing me to skip the 1st While? 那么我可以在第一个选择获得ID并将其传递给第二个选择时让我跳过第一个While的联接或联合吗?

You can make it into single query too. 您也可以使其成为单个查询。

$query = "SELECT `business`.`name`, `business`.`street` 
          FROM `business`, `category` 
          WHERE 
             `business`.`category_id` = `category`.`category_id` 
              AND 
             `category`.`name` = '$searchTerm'";

$searchBus = $mysqli->query($query);
SELECT category_id, category.name 
FROM category c inner join business b using (category_id) 
WHERE category.name = {Term}

Please escape your queries though its currently open to SQL injection 尽管当前可以进行SQL注入,但是请避免查询

You could use the exists operator: 您可以使用exists运算子:

SELECT business.name, business.street 
FROM   business
WHERE  EXISTS (SELECT *
               FROM   category
               WHERE  category.name = '$searchTerm' AND
                      category.category_id = business.category_id)
SELECT business.name, business.street, category.name
FROM business 
JOIN category ON category.category_id = business.category_id
WHERE category.name = '$searchTerm'
SELECT business.name, business.street 
FROM category c, business b
WHERE c.category_id = b.category_id and c.name = '$searchTerm'

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

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