简体   繁体   中英

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 ?!

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

basic sql

SELECT * FROM table WHERE column1 = column2 LIMIT 1

in php you can do the check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM