我有一個拆分選擇語句,我在第一個目標SELECT
中返回給定電子郵件的所有唯一儀表板。如何使用匹配的外鍵值返回唯一對象?
然後第二個SELECT
返回與唯一儀表板的ID相匹配的關聯圖表和KPI外鍵。
所以我做的嘗試是使用兩個選擇之間的UNION
,這給出了一個錯誤All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists
。
我在這裏做了come across a similar issue但在選擇之間添加偶數列值的解決方案不適合這種情況。
問:
你怎麼可以返回唯一對象匹配的外鍵值?
這是我想出了目前的程序,但我接受更好的替代品:
ALTER PROCEDURE [dbo].[GetUserProfile]
@p_email VARCHAR(100)
AS
BEGIN
SELECT UserName, Email, Dashboard_Name, RID from [dbo].[User]
inner join [dbo].[Dashboard] on
[Dashboard].[USER_ID]=[User].Email
and [email protected]_email
UNION
SELECT KPI_Name, Chart_Name FROM [KPI]
inner join [dbo].[Chart] on
[Chart].[KPI_ID]=[KPI].ID
END
而且這是四個表的要點,外鍵約束已經爲簡潔,刪除:
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,
所以這將是預期的結果,如果查詢是正確的:
{
UserName:"brian",
Email:"[email protected]",
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:"[email protected]",
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"
},