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

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

    From the phrasing of your question, I understand that you want to select the distinct values for a given field and for each such value to have all the other column values in the same row listed. Most DBMSs will not allow this with neither DISTINCT nor GROUP BY, because the result is not determined.

    Think of it like this: if your field1 occurs more than once, what value of field2 will be listed (given that you have the same value for field1 in two rows but two distinct values of field2 in those two rows).

    You can however use aggregate functions (explicitely for every field that you want to be shown) and using a GROUP BY instead of DISTINCT:

    SELECT field1, MAX(field2), COUNT(field3), SUM(field4), .... FROM table GROUP BY field1
    

提交回复
热议问题