MySQL结合了几个select语句

时间:2016-10-27 17:24:33

标签: php mysql sql select

想知道如何/如果我可以组合两个选择语句。

        $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

对于输出我只需要Business表中的数据,第一个选择查找搜索到的术语的相关ID,该Id也存放在Business表中。

那么我可以进行第一次选择获取id的连接或联合,然后传递给第二次选择,允许我跳过第一次选择吗?

5 个答案:

答案 0 :(得分:2)

你也可以把它变成单个查询。

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

$searchBus = $mysqli->query($query);

答案 1 :(得分:1)

SELECT category_id, category.name 
FROM category c inner join business b using (category_id) 
WHERE category.name = {Term}

请通过当前打开的SQL注入来逃避您的查询

答案 2 :(得分:1)

您可以使用exists运算符:

SELECT business.name, business.street 
FROM   business
WHERE  EXISTS (SELECT *
               FROM   category
               WHERE  category.name = '$searchTerm' AND
                      category.category_id = business.category_id)

答案 3 :(得分:1)

SELECT business.name, business.street, category.name
FROM business 
JOIN category ON category.category_id = business.category_id
WHERE category.name = '$searchTerm'

答案 4 :(得分:1)

SELECT business.name, business.street 
FROM category c, business b
WHERE c.category_id = b.category_id and c.name = '$searchTerm'