左连接并属于

时间:2016-10-27 10:30:32

标签: php mysql left-join belongs-to

我有三个表:产品(ID,名称),类别(id,name)和 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";
    }

只能使用一个查询进行此操作吗?我尝试使用左连接(产品上的products_categories),但列出了属于多个类别的产品他们所处的每个类别。

修改

以下是一些示例数据

产品表

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

类别表

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

加入表格

+------------+-------------+
| 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.
+------------+--------------+-------------+

1 个答案:

答案 0 :(得分:4)

这只是一个简单的连接问题。我原本以为您可能需要一些查询魔术来显示产品是否属于给定类别。但是,如果您只是使用下面的查询,则可以检查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