
We can use * to select all attribute from table ,I am using distinct and my table contain 16 columns, How can I use distinct with it.I cannot do select distinct Id,* from abc;
What would be the best way.
Another way could be select distinct id,col1,col2 etc.
If you want in the results, one row per
id, you can useGROUP BY id. But then, it’s not advisable to use the other columns in theSELECTlist (even if MySQL allows it – that depends on whether you haveANSIsettingOnorOff). It’s advisable to use the other columns with aggregate functions likeMIN(),MAX(),COUNT(), etc. In MySQL, there is also aGROUP_CONCAT()aggregate function that will collect all values from a column for a group:The query:
is not valid SQL (up to 92) because you have non-aggregated results in the
SELECTlist and valid in SQL (2003+). Still, it’s invalid here because the other columns are not functionally dependent on the grouping column (id). MySQL unfortunately allows such queries and does no checking of functional dependency.So, you never know which row (of the many with same
id) will be returned or even if – horror! – you get results from different rows (with same id). As @Andriy comments, the consequences are that values for columns other thanidwill be chosen arbitrarily. If you want predictable results, just don’t use such a technique.An example solution: If you want just one row from every
id, and you have a datetime or timestamp (or some other) column that you can use for ordering, you can do this:This will work as long as the
(id, some_column)combination is unique.