选择一列作为DISTINCT并回显所有列

时间:2017-05-08 03:31:10

标签: php mysql sql mysqli

我是MySQL的新手。我正在编写一个代码,我需要只选择一个表作为不同的表并返回所有表。

这是我的数据库图片......

这是我的MySQL查询...

`SELECT DISTINCT related_category, pid, id FROM today_offers;

我收到了这个输出......

但我希望它像这样......

related_category | pid | id 
Grocery          | n1  | 1
--------------------------
                 | sp1 | 3
--------------------------
Vegetables       | s1  | 4
--------------------------
Bread & Bakery   | s2  | 5
--------------------------
Food             | ad1 | 6
--------------------------
Kitchen          |acd12| 7
--------------------------

提前致谢!

2 个答案:

答案 0 :(得分:1)

因为我无法评论,所以我需要将此作为答案发布..  1.仅限于'相关类别'

试试这个:

SELECT DISTINCT 'related_category` FROM `today_offers`

答案 1 :(得分:0)

你需要像PHP这样在

这样做

查询:

SELECT`related_category`,`pid`,`id` FROM `today_offers`;

结果数组:

        <?php

    $result = array(array("related_category"=>"Grocery","pid"=>"n1","id"=>1),array("related_category"=>"Grocery","pid"=>"sp1","id"=>3),

                array("related_category"=>"Vegetables","pid"=>"s1","id"=>4),array("related_category"=>"Bread & Bakery","pid"=>"s1","id"=>4),

                 array("related_category"=>"Food","pid"=>"ad1","id"=>6),array("related_category"=>"Kitchen","pid"=>"acd12","id"=>7));

    $new_res = array_unique(array_column($result,'related_category'));

    echo "<table border='1px'>";
    foreach($new_res as $key=>$row)
    {
        $i=0;
        foreach($result  as $key1 =>$row1)
        {
            if($row==$row1['related_category'] && $i==0)
            {
                $i=1;
            ?>  
            <tr>
                <td><?php echo $row1['related_category'] ?></td>
                 <td><?php echo $row1['pid'] ?></td>
                 <td><?php echo $row1['id'] ?></td>

             </tr>   
          <?php
            }
            else if($row==$row1['related_category'] && $i==1)
            {

            ?>  
            <tr>
                <td></td>
                 <td><?php echo $row1['pid'] ?></td>
                 <td><?php echo $row1['id'] ?></td>

             </tr>   
          <?php

            }
        }

    }

    echo "</table>";


    ?>