使用CASE

时间:2017-04-24 09:40:21

标签: sql sql-server case

我正在尝试加入3个表格。

我的第一个表是Order_Header主键Id和两个外键User_IdUser表,Guest_IdGuest

如果在Order_Header表中Guest_Id的值为0,我想使用inner join表执行User,如果User_Id的值为join }是0,我希望Guest使用Select Order_No, [user].Id, [User].Email, [Guest].Id, Guest.Email from Order_Header OH left join [User] on OH.User_Id = [User].Id and OH.User_Id <> 0 left join [Guest] on OH.Guest_Id = [Guest].Id and OH.User_Id = 0 where (case OH.User_Id when 1 then [User].Email else [Guest].Email end as SomeField) 表。

我怎样才能做到这一点?

getEmployeesAsync

3 个答案:

答案 0 :(得分:0)

尝试在选择中使用CASE而不是条件:

Select Order_No, 
  [user].Id,  
  [Guest].Id, 
  CASE WHEN OH.User_Id = 0 THEN [Guest].Email 
       ELSE [User].Email, 
from Order_Header OH
  left join [User] ON OH.User_Id = [User].Id
  left join [Guest] ON OH.Guest_Id = [Guest].Id

答案 1 :(得分:0)

您的查询几乎是正确的,您只在coalesce而不是select子句(语法错误)中遗漏了几个where

Select  Order_No,
        coalesce(usr.Id, [Guest].Id) as someID
        coalesce(usr.Email, Guest.Email) as someEmail
from    Order_Header OH
left join
        [User] as usr
ON      OH.User_Id = usr.Id AND OH.User_Id <> 0
left join
        [Guest] as gst
ON      OH.Guest_Id = gst.Id AND OH.User_Id = 0

这样,您只会有一个ID列和一个Email列,每个列都会填充User的值(如果可用),或者来自Guest

答案 2 :(得分:0)

考虑以下表格定义

<Route component={NoMatch}/>

您可以使用以下查询来获得结果

CREATE TABLE [dbo].[User](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Email] [varchar](max) NULL,
 CONSTRAINT [PK_User] 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] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[Guest](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Email] [varchar](max) NULL,
 CONSTRAINT [PK_Guest] 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] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[Order_Header](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [User_Id] [int] NULL,
    [Guest_Id] [int] NULL,
    [Order_No] [int] NULL,
 CONSTRAINT [PK_Order_Header] 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

ALTER TABLE [dbo].[Order_Header]  WITH CHECK ADD  CONSTRAINT [FK_Order_Header_Guest] FOREIGN KEY([Guest_Id])
REFERENCES [dbo].[Guest] ([Id])
GO

ALTER TABLE [dbo].[Order_Header] CHECK CONSTRAINT [FK_Order_Header_Guest]
GO

ALTER TABLE [dbo].[Order_Header]  WITH CHECK ADD  CONSTRAINT [FK_Order_Header_User] FOREIGN KEY([User_Id])
REFERENCES [dbo].[User] ([Id])
GO

ALTER TABLE [dbo].[Order_Header] CHECK CONSTRAINT [FK_Order_Header_User]
GO