Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct rows without using group by statement

Tags:

sql

mysql

A B C
1 1 1 
1 1 1 
2 2 2 
2 2 2 
3 3 3 
3 3 3 
4 4 4 
4 4 4 
5 5 5 
5 5 5 
5 5 5 
6 6 6
6 6 6 

I am to output only the distinct rows without using the group by statement. I cannot use group by because it makes mysql hang. So it should return

1 1 1
2 2 2 
3 3 3 
4 4 4 
5 5 5 
6 6 6 

I am using DISTINCT in for an inner join.This does not work either:

SELECT DISTINCT * FROM TABLEA inner join TABLEB on TABLEA.A = TABLEB.A 
like image 342
cool_cs Avatar asked Jun 06 '12 21:06

cool_cs


People also ask

How do I use distinct instead of GROUP BY?

When and where to use GROUP BY and DISTINCT. DISTINCT is used to filter unique records out of the records that satisfy the query criteria. The "GROUP BY" clause is used when you need to group the data and it should be used to apply aggregate operators to each group.

How do I SELECT only unique rows in SQL?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

What is alternative for distinct in SQL?

GROUP BY is intended for aggregate function use; DISTINCT just removes duplicates (based on all column values matching on a per row basis) from visibility. If TABLE2 allows duplicate values associated to TABLE1 records, you have to use either option.


1 Answers

SELECT DISTINCT A,B,C FROM TABLE;

According to mysql documentation, DISTINCT specifies removal of duplicate rows from the result set (http://dev.mysql.com/doc/refman/5.0/en/select.html)

I created a sample on jsfiddle and it works IMHO

create table tablea (A int,B int,C int);
create table tableb (A int);

INSERT INTO tablea VALUES (1,1,1),(1,1,1),(2,2,2),(2,2,2),(3,3,3),(3,3,3),(4,4,4),(4,4,4),(5,5,5),(5,5,5),(5,5,5),(6,6,6),(6,6,6);
INSERT INTO tableb VALUES (1),(1),(1),(1),(1);

SELECT DISTINCT tablea.A,tablea.B,tablea.C FROM tablea INNER JOIN tableb ON tablea.A=tableb.A;

feel free to experiment on this SQLFiddle.

like image 115
Jerome WAGNER Avatar answered Oct 18 '22 09:10

Jerome WAGNER