SQL获取ID之间的连接

时间:2015-07-10 08:07:45

标签: mysql sql join

我们有那个数据表:

id | parent_id

124    510

124    407

125    504

126    508

我想要作为510的孩子返回407的结果:

id | childOfparent_id | parent_id 

124    407       510
125    NULL      504
126    NULL      508

我怎么能做到这一点?我尝试使用id进行分组并计算distnict值但没有成功。

Child的id值较低:4xx低于5xx。我正在使用mysql。

2 个答案:

答案 0 :(得分:0)

为孩子做最低值GROUP BY,为父母做最高值:

select id, min(parent_id) as childOfparent_id, max(parent_id) as parent_id
from tablename
group by id
having min(parent_id) <> max(parent_id) 

您也可以自我LEFT JOIN

select t1.id, t2.parent_id as childOfparent_id, t1.parent_id as parent_id
from tablename t1
  left join tablename t2 on t1.id = t2.id and t1.parent_id > t2.parent_id

如果不存在儿童,将返回NULL

答案 1 :(得分:0)

declare @t table (Id int,parent_id int)

insert into @t(Id,parent_id) values (124,510),(124,407)
;with CTE AS (
select Id,parent_id,ROW_NUMBER()OVER(PARTITION BY id ORDER BY ID)R from @t)
select T.Id,T.parent_id,TT.parent_id As ChildId from 
(
Select ID,parent_id from CTE where R = 1)T,(
Select ID,parent_id from CTE where R = 2)TT