SQL/mysql - Select distinct/UNIQUE but return all

2018-12-31 17:20发布

SELECT DISTINCT field1, field2, field3, ......   FROM table

I am trying to accomplish the following sql statement but I want it to return all columns is this possible? Something like:

SELECT DISTINCT field1, * from table

15条回答
步步皆殇っ
2楼-- · 2018-12-31 17:58
SELECT * from table where field in (SELECT distinct field from table)
查看更多
零度萤火
3楼-- · 2018-12-31 17:59

I would suggest using

SELECT  * from table where field1 in 
(
  select distinct field1 from table
)

this way if you have the same value in field1 across multiple rows, all the records will be returned.

查看更多
梦寄多情
4楼-- · 2018-12-31 18:01

Just include all of your fields in the GROUP BY clause.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 18:02

It can be done by inner query

$query = "SELECT * 
            FROM (SELECT field
                FROM table
                ORDER BY id DESC) as rows               
            GROUP BY field";
查看更多
查无此人
6楼-- · 2018-12-31 18:03
SELECT  c2.field1 ,
        field2
FROM    (SELECT DISTINCT
                field1
         FROM   dbo.TABLE AS C
        ) AS c1
        JOIN dbo.TABLE AS c2 ON c1.field1 = c2.field1
查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 18:03

You can do it with a WITH clause.

For example:

WITH c AS (SELECT DISTINCT a, b, c FROM tableName)
SELECT * FROM tableName r, c WHERE c.rowid=r.rowid AND c.a=r.a AND c.b=r.b AND c.c=r.c

This also allows you to select only the rows selected in the WITH clauses query.

查看更多
登录 后发表回答