Mohammad
Mohammad

Reputation: 179

Select second record from table matching with first record

How select first record and matching with second record ?!

Samlpe:

1- A
2- A
3- B
4- C

This code match 1 and 2 , and return TRUE

How write query ?!

Upvotes: 1

Views: 93

Answers (2)

Filipe Silva
Filipe Silva

Reputation: 21657

To get the ID's of the rows that have the duplicate values on the second column you can do:

SELECT t1.id,t2.id
FROM tab1 t1
INNER JOIN tab1 t2 ON t1.val = t2.val AND t1.id <> t2.id;

To get TRUE when there are at least two rows that have the same value on the second column you or FALSE otherwise, you can do:

SELECT CASE 
    WHEN numEquals <> 0 THEN 'TRUE'
    ELSE 'FALSE' END AS HasEquals
FROM (
  SELECT COUNT(*) AS numEquals
  FROM tab1 t1
  INNER JOIN tab1 t2 ON t1.val = t2.val AND t1.id <> t2.id
  ) a

sqlfiddle demo

Upvotes: 2

Bokw
Bokw

Reputation: 799

basic sql

SELECT * FROM table WHERE column1 = column2 LIMIT 1

in php you can do the check

Upvotes: 0

Related Questions