PHP MySQL在多个类别中查询多个产品

时间:2015-11-29 18:06:13

标签: php mysql sql

我想从数据库输出如下:

Store name 1
--------------------
Product 1
Product 2

Store name 2
---------------------
Product 3
Product 4

我现在使用的查询如下所示:

$query_stores = DB::query("SELECT * FROM `stores` LIMIT 16");

foreach($query_stores as $row){

   echo $row['name'] . '<br>';

   $query_products = DB::query("SELECT `id`, `name` FROM `products` WHERE `vendor` = %i ORDER BY RAND() LIMIT 10" , $row['id']);

   foreach($query_products as $row2){
      echo $row2['name'] . '<br>';
   }
}

代码有效(但有点),但我无法过滤stores表中没有任何项目的products

示例输出:

Store name 1

Store name 2
    --------------------
    Product 1
    Product 2

Store name 3

Store name 4
    ---------------------
    Product 3
    Product 4

Store name 5

有没有更好的方法来运行代码?这两个查询可以合并吗?

如何从stores表格中没有任何项目的输出中排除products

3 个答案:

答案 0 :(得分:1)

最好使用带有join语句的单个查询,并构建一个数据数组来解析和显示:

$sql = "SELECT s.id as store_id, s.name as store_name, p.id as product_id, p.name as product_name
            FROM stores s 
            LEFT JOIN products p ON (s.id = p.vendor)
            WHERE p.id IS NOT NULL
            ORDER BY s.name ASC, p.name ASC
            LIMIT 16";
$data = DB::query($sql);

运行查询后,$data将仅包含具有产品的商店。 LEFT JOIN将确保商店是基本信息,如果商品没有商品,则产品列将为NULLWHERE子句确保您过滤掉任何没有产品的商店。

设置结构化数组可以更轻松地循环数据。

$stores = []; // or if PHP version < 5.4 array();
foreach($data as $row) {
    if (!array_key_exists($row['store_id'], $stores)) {
        $stores[$row['store_id']] = [
            'store_name' => $row['store_name'],
            'products' => [],
        ];
    }

    $stores[$row['store_id']]['products'][$row['product_id']] = $row['product_name'];
}

输出:

foreach ($stores as $store_id => $store) {
    echo $store['name'] .'<br/>';
    foreach ($store['products'] as $product_id => $product_name) {
        echo $product_name .'<br/>';
    }
}

答案 1 :(得分:0)

尝试这样的方法对您的查询进行重新排序,这样您就可以检查商店是否为空,然后如果不是则打印,如果为空,则不要打印它。

$query_stores = DB::query("SELECT * FROM `stores` LIMIT 16");

foreach($query_stores as $row){
    // put $query_products in front of echoing  and check if store is empty

    $query_products = DB::query("SELECT `id`, `name` FROM `products` WHERE `vendor` = %i ORDER BY RAND() LIMIT 10" , $row['id']);
    // Here you check if result is empty
    if(mysql_num_rows($query_products) > 0){
        echo $row['name'] . '<br>';   

        foreach($query_products as $row2){
            echo $row2['name'] . '<br>';
        }
    }
}

答案 2 :(得分:-1)

你可以使用mysql_num_rows();功能并检查结果的数量是否为&lt; 0