【问题标题】:PHP unique values from fetch_assoc()来自 fetch_assoc() 的 PHP 唯一值
【发布时间】:2014-05-17 16:22:11
【问题描述】:

我有一个产品数据库,每个产品都有 1 个或多个标签。比如我的查询结果是:

//Query results
product_id  tag
12345       Kitchen
12345       Mixer
12345       Baking

如何显示给定产品的所有标签,并且只列出一次产品,以便我的输出类似于:

Product ID: 12345 
Tags: Kitchen Mixer Baking

目前,我正在使用fetch_assoc() 并循环遍历仅显示所有内容的行。完成此任务的最佳方法是什么?

以下是我当前的代码:

$sql = <<<SQL
    SELECT p.product_id, t.tag
    FROM products p
    JOIN tags t
    ON p.product_id = t.product_id
    WHERE p.product_id='12345'
SQL;

$db = new mysqli('localhost', 'user', 'password', 'dbname');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

while($row = $result->fetch_assoc()){
    echo $row['product_id'] . '<br>';
    echo $row['tag'] . '<br>';
}

【问题讨论】:

    标签: php mysqli unique


    【解决方案1】:

    使用GROUP_CONCAT()函数:

    SELECT p.product_id, GROUP_CONCAT(t.tag)
    FROM products p
    JOIN tags t
    ON p.product_id = t.product_id
    WHERE p.product_id='12345'
    GROUP BY p.product_id
    

    【讨论】:

    • 谢谢!这很简单。
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多