[英]Mysql select the same values in different rows and different column
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 在 old_id 和 new_id 中具有相同值的行,所以我的 select 应该从示例中返回第 1 行和第 4 行
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
:我只会使用
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)
.特别是,这可以利用
(old_id)
和(new_id)
上的索引。 With those indexes, this should be the fastest solution.有了这些索引,这应该是最快的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.