mysql> select * from a; +------+-------+ | a_id | a_val | +------+-------+ | 1 | 1 | | 2 | 3 | | 3 | 3 | | 4 | 4 | | 5 | 6 | | 6 | 7 | | 7 | 8 | +------+-------+ 7 rows in set (0.00 sec) mysql> select * from b; +------+-------+-------+ | b_id | b_val | a_val | +------+-------+-------+ | 1 | 1 | 2 | | 2 | 4 | 2 | | 3 | 2 | 4 | | 4 | 7 | 4 | | 5 | 12 | 6 | +------+-------+-------+ 5 rows in set (0.00 sec) mysql> select a.a_id, b.b_id from a left join b on b.a_val=a.a_id left join b as b_tmp on (b_tmp.a_val=a.a_id and b_tmp.b_id > b.b_id) where b_tmp.b_id IS NOT NULL order by a.a_id asc; +------+------+ | a_id | b_id | +------+------+ | 2 | 1 | | 4 | 3 | +------+------+ 2 rows in set (0.00 sec)