简体   繁体   中英

Mysql select distinct id's and select first row only

This is my table. I want to select distinct 'bill_no' with only first related row.

    +--------------+--------------+-------+------------+
    | id | bill_no | product_name | tax   | total      | 
    +--------------+-------+------+-------+------------+
    | 1  |    12   |   Hairgel    |  10   |        241 |      
    | 2  |    12   |  Spiker gel  |  10   |        300 |      
    | 3  |    13   | Wokzem amba  |  12   |        450 |      
    | 4  |    13   | test prod    |  1    |        145 |      
    | 5  |    14   | wokk         |  3    |         55 |   
    | 6  |    14   | Kamer hyp    |  11   |         46 |      
    | 7  |    15   | Xyombokx     |  2    |        220 |     
    +--------------+-------+------+-------+------------+

I want data to be displayed like the below table having only distinct "bill_no" -

Output-

    +--------------+--------------+-------+------------+
    | id | bill_no | product_name | tax   | total      | 
    +--------------+-------+------+-------+------------+
    | 1  |    12   |   Hairgel    |  10   |        241 |                
    | 3  |    13   | Wokzem amba  |  12   |        450 |           
    | 5  |    14   | wokk         |  3    |         55 |         
    | 7  |    15   | Xyombokx     |  2    |        220 |     
    +--------------+-------+------+-------+------------+

使用group by

select * from youtable group by bill_no
select t1.* 
from your_table t1
join
(
  select min(id) as id
  from your_table
  group by bill_no
) t2 on t1.id = t2.id

您可以使用GROUP BY子句.GROUP BY子句始终按cloumn名称返回具有相关组的第一行。

SELECT * FROM `table_1` group by `bill_no` 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM