简体   繁体   中英

SQL Create new column based on self join

Here is the Data below:

Name Parent Age
John Mary 12
Mary None 23

I want to create a new column called Parent's Age so that John's row will now have a column called Parent's age and it would be 23. Mary would have none as Parent's age.

I've tried joining the table to itself on Name = Parent but the wrong age is pulled.

First of all you should use ID's as primary and foreign keys as it's high likely, that there are more people with the name Mary and that will end up in wrong joins.

Afterwards you can create a view where every person with the related parent data is shown. It's bad practice to store that as physical column in the person table.

An example for MS SQL Server:

CREATE TABLE [dbo].[tblPerson](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentID] [int] NULL,
    [Name] [nvarchar](255) NULL,
    [Age] [int] NULL
 CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

insert into tblPerson(ParentID, [Name], Age) values(NULL, 'Marry', 23);
insert into tblPerson(ParentID, [Name], Age) values(1, 'John', 12);

select 
    child.[Name] as [Child Name], 
    child.Age as [Child Age],
    parent.[Name] as [Parent Name],
    parent.Age as [Parent Age]
from tblPerson child
left join tblPerson parent on child.ParentID = parent.ID

In addition it's also bad practise to store the age... much better is to store the birthdate and calculate the age out of that.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM