sql server - How to return unique objects with matching foreign key values? -


i have split select statement i'm aiming in first select return unique dashboards given email.

then second select return associated charts , kpi foreign keys matching id of unique dashboard.

so did try using union between 2 selects, gives error all queries combined using union, intersect or except operator must have equal number of expressions in target lists.

i did come across similar issue here solution of adding number of column values between selects doesn't suit situation.

question:

how can return unique objects matching foreign key values?

this current procedure came i'm open better alternatives:

alter procedure [dbo].[getuserprofile]    @p_email varchar(100)      begin                 select username, email, dashboard_name, rid [dbo].[user]               inner join [dbo].[dashboard]  on               [dashboard].[user_id]=[user].email               , email=@p_email               union               select kpi_name, chart_name [kpi]           inner join [dbo].[chart] on               [chart].[kpi_id]=[kpi].id     end 

also gist of 4 tables, foreign key constraints have been removed brevity:

 table [dbo].[user]( [id] [int] identity(1,1) not null, [username] [varchar](50) not null, [email] [varchar](80) not null,           table [dbo].[dashboard]( [id] [int] identity(1,1) not null, [dashboard_name] [varchar](100) not null, [rid] [nvarchar](255) not null, [user_id] [varchar](80) not null   table [dbo].[kpi]( [id] [int] identity(1,1) not null, [kpi_name] [varchar](100) not null, [dashboardid] [int] not null,   table [dbo].[chart]( [id] [int] identity(1,1) not null, [chart_name] [varchar](100) not null, [kpi_id] [int] not null, 

so expected outcome if query correct:

{      username:"brian",    email:"brian@gmail.com",    dashboard_name:"test dash 1",    rid:"2003",    dashboardid:1,    kpi_name:"test kpi 1",    kpi_id:1,    chart_id:1,    chart_name:"ch1, ch2, ch3" }, {      username:"brian",    email:"brian@gmail.com",    dashboard_name:"test dash 2",    rid:"2003",    dashboardid:2,    kpi_name:"test kpi 2",    kpi_id:2,    chart_id:2,    chart_name:"ch4, ch5, ch6" }, 

your union won't work stated above. try this.

select username, email, dashboard_name, rid, dashboard.id dashboard_id, kpi_name, kpi.id kpi_id,chart.id chart_id, chart_name   [user]   inner join [dashboard]  on [dashboard].[user_id]=[user].email               , [user].email=@p_email    inner join [kpi] on [dashboard].[dashboard_id] = [kpi].[dashboard_id]   inner join [chart] on [kpi].[id] = [chart].[kpi_id] 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -