左加入并属于

Left join and belongs to

我有三个 tables:products (id, name), categories (id, name) and products_categories (product_id, category_id).

每个产品属于一个或多个类别。

我想检索所有产品,并显示哪些已经在类别 "X" 中。 我的 div 是这样的:

   <span>Category "X"</span>
   [some php / fetch_assoc() / … ]
   <div class="product">Product A</div>
   <div class="product selected">Product B</div>
   <div class="product">Product B</div>

目前,它处理两个查询:一个用于获取所有产品,一个用于检查产品是否在 products_categories 中。所以这是很多小查询,第一个里面有 php。

$getAllProducts = "SELECT products.name as productName, products.id as productID FROM products";
$resultProduct=$mysqli->query($getAllProducts);
while($product=$resultProduct->fetch_assoc()){
    $reqChecked = "SELECT * FROM products_categories
                   WHERE product_id=" .  $product["productID"] ."
                   AND category_id=" . $category["id"]; //$category["id"] is given
    $resultChecked = $mysqli->query($reqChecked);
    $row = $resultChecked->fetch_row();
    $selected = ""
    if ( isset($row[0]) ) {
        $selected = "selected";
    }

只用一个查询就可以做到吗? 我试过 left join(products_categories 在产品上),但属于多个类别的产品会针对它们所在的每个类别列出。

编辑

这是一些示例数据

产品table

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | product_1 |
|  2 | product_2 |
|  3 | product_3 |
+----+-----------+

类别table

+----+------------+
| id |    name    |
+----+------------+
|  1 | category_1 |
|  2 | category_2 |
|  3 | category_3 |
+----+------------+

加入table

+------------+-------------+
| product_id | category_id |
+------------+-------------+
|          1 |           1 |
|          1 |           2 |
|          2 |           2 |
+------------+-------------+

现在,假设我正在编辑页面 category_2,我想要以下结果:

+------------+--------------+-------------+
| product_id | product_name | category_id |
+------------+--------------+-------------+
|          1 | product_1    | 2           | --product_1 belongs to category_1 and category_2, but I only need it one time.
|          2 | product_2    | 2           |
|          3 | product_3    | NULL        | --product_3 belongs to nothing but I want to see it.
+------------+--------------+-------------+

这只是一个简单的连接问题。我最初认为您可能需要一些查询魔法来显示产品是否属于给定类别。但是,如果您只使用下面的查询,您可以检查 PHP 中每一行的类别名称并采取相应的措施。

SELECT p.id,
       p.name AS product,
       c.name AS category       -- check for value 'X' in your PHP code
FROM products p
INNER JOIN products_categories pc
    ON p.id = pc.product_id
INNER JOIN categories c
    ON c.id = pc.category_id

请注意,您当前的方法实际上是尝试在 PHP 代码本身中进行连接,出于多种原因,这是不可取的。

更新:

SELECT t1.id AS product_id,
       t1.name AS product_name,
       CASE WHEN t2.productSum > 0 THEN '2' ELSE 'NA' END AS category_id
FROM products t1
LEFT JOIN
(
    SELECT product_id,
           SUM(CASE WHEN category_id = 2 THEN 1 ELSE 0 END) AS productSum
    FROM products_categories
    GROUP BY product_id
) t2
    ON t1.id = t2.product_id