如何从Coma Seperated mysqli Query中选择DISTINCT

时间:2016-06-02 14:49:25

标签: php mysqli

Hello Guys我的桌子上有coma separated entries。我想使用DISTINCT函数来获得唯一的结果。我有像

这样的条目
id | name
1  | sachin tendulkar, virat kohli, ms dhoni
2  | ms dhoni, vvs laxman, ajinkya rahane
3  | rohit sharma, virat kohli, ms dhoni

我想使用mysqli来显示

等结果
name : sachin tendulkar, virat kohli, ms dhoni, 
       vvs laxman, ajinkya rahane, rohit sharma

如果它们相同,我不想重复这些名称。

我试过了:

$catquery = $db->query("SELECT DISTINCT name FROM players WHERE id='$id';");
while($row2 = $catquery->fetch_object()):
echo "$row2->name";
endwhile;

但结果如下:

sachin tendulkar, virat kohli, ms dhoni 
ms dhoni, vvs laxman, ajinkya rahane 
rohit sharma, virat kohli, ms dhoni

找不到唯一的名字,请帮助我解决它!

2 个答案:

答案 0 :(得分:0)

您需要在PHP端处理它。

$catquery = $db->query("SELECT name FROM players WHERE id='$id';");

$names = [];    //Collect name to this
while($row2 = $catquery->fetch_object()) {
    $pieces = explode(',',$row2->name); //explode the string by ',' character
    foreach ($pieces as $piece) {
        $names [] = trim($piece);
    }

}
var_dump(array_unique($names)); //here is the uniqe array

如果您确定,可以按,(逗号和空格)展开它,逗号后总是有空格。

如果您回到第1行,因为id是主键,则不需要while

答案 1 :(得分:0)

最好制作一个阵列并一次回显它

$unique_names = [];
$catquery = $db->query("SELECT DISTINCT name FROM players WHERE id='$id';");
while($row2 = $catquery->fetch_object()):
  $unique_names = array_merge($unique_names, array_map('trim',explode(',',$row2->name)));
endwhile;

$unique_names = array_unique($unique_names);
echo implode(',',$unique_names);

最后,$ unique_names数组中包含所有唯一名称。例如,我崩溃了并且回应了。您可以按自己的方式使用它

这是在评论中添加的请求:

foreach($unique_names as $unique_name){
  echo '<a href="/player.php?player='. str_replace(' ','-',$unique_name) .'">'.$unique_name.'</a><br>';
}