我需要在同一行的单个孩子的单独列中获取每个父ID。我有一个建立子/父关系的表,但数据的结构是每行一个子/父关系。
我尝试了CREATE TABLE
语句,但这并不总是一种选择,因为我并不总是具有创建数据库的权限。我主要只有只读权限。
预期结果如下:
2 | 1053 | Mother | 14059 | Father
2 =子ID
答案 0 :(得分:1)
您可以使用自我联接:
select m.personID1 as childid,
m.personID2 as mother_id,
m.name as mother_name,
f.personID2 as father_id,
f.name as father_name
from the_table m
join the_table f on m.personID1 = f.personID1 and f.name = 'Father'
where m.personID = 2
and m.name = 'Mother';
答案 1 :(得分:1)
您可以group by personid1
和条件聚合:
select
personid1,
max(case name when 'Mother' then personid2),
'Mother',
max(case name when 'Father' then personid2),
'Father'
from tablename
group by personid1
也许应该添加WHERE子句以将行限制为仅学生ID。