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

前端 未结 18 936
忘掉有多难
忘掉有多难 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:31

    Great question @aryaxt -- you can tell it was a great question because you asked it 5 years ago and I stumbled upon it today trying to find the answer!

    I just tried to edit the accepted answer to include this, but in case my edit does not make it in:

    If your table was not that large, and assuming your primary key was an auto-incrementing integer you could do something like this:

    SELECT 
      table.*
    FROM table
    --be able to take out dupes later
    LEFT JOIN (
      SELECT field, MAX(id) as id
      FROM table
      GROUP BY field
    ) as noDupes on noDupes.id = table.id
    WHERE
      //this will result in only the last instance being seen
      noDupes.id is not NULL
    

提交回复
热议问题