SQL/mysql - Select distinct/UNIQUE but return all columns?

前端 未结 18 940
忘掉有多难
忘掉有多难 2020-11-22 12:08
SELECT DISTINCT field1, field2, field3, ......   FROM table

I am trying to accomplish the following sql statement but I want it to return all colum

相关标签:
18条回答
  • 2020-11-22 12:35

    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.

    0 讨论(0)
  • 2020-11-22 12:36
    select min(table.id), table.column1
    from table 
    group by table.column1
    
    0 讨论(0)
  • 2020-11-22 12:40
    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
    
    0 讨论(0)
  • 2020-11-22 12:41

    You're looking for a group by:

    select *
    from table
    group by field1
    

    Which can occasionally be written with a distinct on statement:

    select distinct on field1 *
    from table
    

    On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)

    You could fetch the distinct fields and stick to picking a single arbitrary row each time.

    On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:

    select *
    from (
       select *,
              row_number() over (partition by field1 order by field2) as row_number
       from table
       ) as rows
    where row_number = 1
    

    On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.

    0 讨论(0)
  • 2020-11-22 12:41
    SELECT * from table where field in (SELECT distinct field from table)
    
    0 讨论(0)
  • 2020-11-22 12:42

    Try

    SELECT table.* FROM table 
    WHERE otherField = 'otherValue'
    GROUP BY table.fieldWantedToBeDistinct
    limit x
    
    0 讨论(0)
提交回复
热议问题