Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting distinct pairs in MySQL

Tags:

mysql

distinct

I would like to select the rows that has the same values across column A and column B.

For example if my table is:

-----
A | B
-----
1 | 2
3 | 4
1 | 2
4 | 5

The output should be:

A  B
1  2
  • [A] SELECT DISTINCT A, B FROM table;
    Selects all the values in the table.
  • [B] SELECT DISTINCT (A, B) FROM table;
    Tells me that Distinct function can take only one value.
  • [C] SELECT A, B FROM table GROUP BY A, B;
    Selects all the values in the table (Similar to A).

The question is similar to Selecting Distinct combinations., but the answer suggested there doesn't work.

like image 754
Ank Avatar asked Aug 17 '12 22:08

Ank


People also ask

How do you find distinct pairs in SQL?

To get the identical rows (based on two columns agent_code and ord_amount) once from the orders table, the following SQL statement can be used : SQL Code: SELECT DISTINCT agent_code,ord_amount FROM orders WHERE agent_code='A002';

Can I use distinct in where clause MySQL?

How Can we use MySQL DISTINCT clause with WHERE and LIMIT clause? By using the WHERE clause with a DISTINCT clause in MySQL queries, we are putting a condition on the basis of which MySQL returns the unique rows of the result set.

What is distinct clause in MySQL?

MySQL DISTINCT clause is used to remove duplicate records from the table and fetch only the unique records. The DISTINCT clause is only used with the SELECT statement. Syntax: SELECT DISTINCT expressions.


1 Answers

You want only the rows which have duplicates. You can use the HAVING clause to filter "groupings" of data based on aggregation functions:

SELECT   A,B
FROM     tbl
GROUP BY A,B
HAVING   COUNT(*) > 1
like image 60
Zane Bien Avatar answered Sep 19 '22 15:09

Zane Bien