简体   繁体   中英

SQL statement for displaying unique values

Below is the data in my table:

TABLE:
abc-ac                     
abc-dc                     
aax-i                      
bcs-o-dc                   
ddd-o-poe-dc               

I need to write a query which will display only the unique entries as a result:

abc-ac
aax-i                      
bcs-o-dc                   
ddd-o-poe-dc

So basically, since the first two entries start with "abc", it should be treated as one and displayed.

Thanks.

If you're not picky about which one of the two abc-* records that it shows you can use this:

SELECT f1 FROM mytable GROUP BY substring_index(f1, '-', 1)

SQLFiddle Here

That substring_index() function will split the value in your field by - and return the first bit. So essentially your records get grouped by only the first part. This is one of the few times that we can take advantage of MySQLs strange GROUP BY behavior where it will allow you to leave out non-aggregated fields from the group by.

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