我有一个sql请求,使用mysqli_fetch_all
检索数据库中具有其类别的所有产品,当一个产品具有两个类别,而我返回的结果是该产品的两倍,或者是该类别的n倍时,就会出现问题该产品具有该功能,如果有人用php或sql向我解释了如何做我希望的功能,则我无法在html模板中正确输出该产品。
products
--------
id
name
etc ...
categories
----------
id
name
category_product
----------------
category_id
product_id
$sql = "SELECT
p.id,
p.name,
p.price,
categories.name as category_name
FROM products as p
JOIN category_product
ON p.id = category_product.product_id
JOIN categories
ON category_product.category_id = categories.id";
output => [0] => Array (
[id] => 3
[name] => product 3
[price] => 1.00
[category_name] => cat 4 )
[1] => Array (
[id] => 3
[name] => product 3
[price] => 1.00
[category_name] => cat 3 )
expected => [0] => Array (
[id] => 3
[name] => product 3
[price] => 1.00
[category_name] => Array(
[0] => cat 3
[1] => cat 4 ]))
答案 0 :(得分:2)
更改查询以生成类别名称的GROUP_CONCAT
,然后在获取后可以在PHP中使用explode
拆分该值。例如(假设您在连接MySQLi
上使用$conn
):
$sql = "SELECT
p.id,
p.name,
p.price,
GROUP_CONCAT(categories.name SEPARATOR '|') as category_name
FROM products as p
JOIN category_product ON p.id = category_product.product_id
JOIN categories ON category_product.category_id = categories.id
GROUP BY p.id, p.name, p.price";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc()) {
// split the category names into an array
$row['category_name'] = explode('|', $row['category_name']);
// do something with the row value
}
请注意,您需要为GROUP_CONCAT
指定一个分隔符(在这种情况下,我使用了|
),该分隔符不会出现在类别名称中。