【问题标题】:SQL/PHP join products table on multiple images tableSQL/PHP 在多个图像表上连接产品表
【发布时间】:2018-11-04 15:03:13
【问题描述】:

我有两张表格产品图片)。图像中每个产品都没有、一个甚至更多的记录。

我想将两张图片(如果有)加入每个产品并以某种方式显示它们。我说的是产品列表不是单一产品。问题来了。

假设我有这些表:

产品:

id     | name
1      | Lenovo V310
2      | Adapter 5v
3      | Mousepad
4      | Gamepad Logitech
5      | Nokia 3210

图片:

id      | image_name    | product_id
1       | lenovo1.jpg   | 1
2       | lenovo2.jpg   | 1
3       | lenovo3.jpg   | 1
4       | lenovo4.jpg   | 1
5       | mousepad1.jpg | 3
6       | mousepad2.jpg | 3
7       | gamepad1.jpg  | 4
8       | gamepad2.jpg  | 4
9       | nokia1.png    | 5
10      | nokia2.png    | 5
11      | nokia3.png    | 5
12      | nokia4.png    | 5

我希望我的产品(产品列表不是单个项目)以每张两张图片显示:

示例:联想V310 + lenovo1.jpg + lenovo2.jpg

我尝试了一些方法,但没有奏效。比如:

    $q = "SELECT products.id, products.name, images.image_name FROM products LEFT JOIN images ON products.id = (SELECT product_id FROM images) LIMIT 6";
    $query = mysqli_query($dbc, $q);
    while ($row = mysqli_fetch_assoc($query)) {
        $id = $row['id'];
        $name = $row['name'];
        $image1 = $row['image_name']; // ain't working also with the query above
        $image2 = $row['image_name']; // how to take the second img????
        ..............

【问题讨论】:

标签: php sql join


【解决方案1】:

你可以使用GROUP_CONCAT来做到这一点

SQL:

SELECT p.id,
    p.name,
    GROUP_CONCAT(i.image_name ORDER BY i.image_name) AS images
FROM products p
LEFT JOIN images i ON p.id = i.product_id
GROUP BY p.id
LIMIT 6;

PHP:

$query = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($query)) {
    $id = $row['id'];
    $name = $row['name'];
    $images = explode(',', $row['images']);
    $image1 = (count($images) > 0) ? $images[0] : null;
    $image2 = (count($images) > 1) ? $images[1] : null;
}

【讨论】:

  • 我建议$images = explode(',', $row['images']);,然后根据需要从该数组中分配$image1$image2。另外:为什么你的查询中有LIMIT 6
  • 同意@DaanWilmer 谢谢。已更新答案。对于LIMIT 6,它在原始查询中,所以我保留了它。
  • 我刚刚尝试了解决方案。现在我有一些新东西要研究:) GROUP_CONCAT。有趣的。对于一个新手来说,这并不容易。关于您关于 LIMIT 6 的问题 - 想象一下首页上最畅销的 6 款产品。哪里有什么特别之处。对不起,如果它让你感到困惑。您可能认为我试图限制某些图像或其他内容。做得很好。干杯
  • 嗨,我同意这并不容易,我在 PHP 开发方面有七年的经验后发现了GROUP_CONCAT,请记住它是一个分组函数,就像 SUMMAX函数,因此您通常会有一个包含重复值的列(此处为 p.id 列)并与此列分组,然后您对分组在其他列上的值执行您想要的操作(这里我们感兴趣的是i.image_name 列)。
  • @ankabout 另外,如果有人知道我应该在哪里插入 WHERE 子句,请告诉我。我想只显示活跃的产品,所以我尝试在一些不同的位置插入WHERE products.status = 1,但是查询失败了。
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 2015-08-29
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多