new_id old_id
000 333
111 666
222 555
333 777
I want to select the rows with the same values in old_id and new_id so my select should return row 1 and 4 from the example
SELECT *
FROM `table` AS `t`
INNER JOIN ( SELECT * FROM `table` ) as `old`
ON `old`.`old_id` = `t`.`new_id`
I have this query but it doesn't work it just returns all the records
Try this below logic-
SELECT DISTINCT C.* FROM
(
SELECT A.new_id
FROM your_table A
INNER JOIN your_table B ON A.new_id = B.Old_id
)A
INNER JOIN your_table C
ON A.new_id = C.new_id
OR A.new_id = C.old_id
I would just use exists
:
select t.*
from t
where exists (select 1
from t t2
where t2.new_id = t.old_id
) or
exists (select 1
from t t2
where t2.old_id = t.new_id
) ;
In particular, this can take advantage of indexes on (old_id)
and (new_id)
. With those indexes, this should be the fastest solution.
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.