使用INNER JOIN AND OR编写查询

时间:2014-05-13 19:26:21

标签: sql sql-server

我有一个表单和一个插入按钮,当我点击按钮时 - 字段会进入这些表格(我没有把所有字段放在这里,因为它们对我的问题不重要)。

表格:

CREATE TABLE SafetyAct (
SafetyAct_id int identity(1,1),
Username varchar(50),
SafetyType_id int,
constraint pk_SafetyAct_id 
           primary key (SafetyAct_id),
constraint fk_Users_SafetyAct 
           foreign key(Username) 
           references Users(Username)
           on delete cascade
)
CREATE TABLE Product (
Product_id int identity(1,1) primary key,
SafetyAct_id int,
Cause_id int,
constraint fk_SafetyAct_Product
           foreign key(SafetyAct_id)
           references SafetyAct(SafetyAct_id)
           on delete cascade,
constraint fk_Cause_Product
           foreign key(Cause_id)
           references Cause(Cause_id) 
           on delete cascade
)
CREATE TABLE SafetyIntervention (
SafetyIntervention_id int identity(1,1) primary key,
SafetyAct_id int,
Cause_id int,
constraint fk_SafetyAct_SafetyIntervention 
           foreign key(SafetyAct_id)
           references SafetyAct(SafetyAct_id)
           on delete cascade,
constraint fk_Cause_SafetyIntervention
           foreign key(Cause_id)
           references Cause(Cause_id)
           on delete cascade
)
CREATE TABLE Cause (
Cause_id int primary key,
Cause_name varchar(80)
)

我想编写一个显示字段的查询 - SafetyAct_id和Cause_name。 在Cause_name字段中我有一个问题,因为我希望查询将显示原因名称drom来自SafetyIntervension表的产品表(当然要将它连接到Cause表,因为我只有这些表中的cause_id - foriegn键)并且我不知道如何在同一查询中编写INNER JOIN和OR。

我是新手,所以请耐心等待。

谢谢!

2 个答案:

答案 0 :(得分:0)

SELECT  SA.SafetyAct_id,
        C.Cause_name
FROM SafetyAct SA
LEFT JOIN Product P
    ON SA.SafetyAct_id = P.SafetyAct_id
LEFT JOIN SafetyIntervention SI
    ON SA.SafetyAct_id = SI.SafetyAct_id
LEFT JOIN Cause C
    ON ISNULL(P.Cause_id,SI.Cause_id) = C.Cause_id

答案 1 :(得分:0)

or很简单。所以,基于Lamak的代码:

SELECT SA.SafetyAct_id,
       C.Cause_name
FROM SafetyAct SA LEFT JOIN
     Product P
     ON SA.SafetyAct_id = P.SafetyAct_id LEFT JOIN
     SafetyIntervention SI
     ON SA.SafetyAct_id = SI.SafetyAct_id LEFT JOIN
     Cause C
     ON C.Cause_id = P.Cause_id OR C.Cause_Id = SI.Cause_id;
--------------------------------^

您可以在OR条件中使用ON

但是,当join条件包含on条件或用于连接的列上的函数时,SQL引擎(包括SQL Server)优化or通常具有挑战性。因此,以下内容通常更有效:

SELECT SA.SafetyAct_id,
       COALESCE(Cp.Cause_name, Csi.Cause_Name) as Cause_Name
FROM SafetyAct SA LEFT JOIN
     Product P
     ON SA.SafetyAct_id = P.SafetyAct_id LEFT JOIN
     SafetyIntervention SI
     ON SA.SafetyAct_id = SI.SafetyAct_id LEFT JOIN
     Cause Cp
     ON Cp.Cause_id = P.Cause_id LEFT JOIN
     Cause Csi
     ON Csi.Cause_Id = SI.Cause_id;

如果只有部分记录有两种类型的原因,请添加:

WHERE Cp.Cause_Id IS NOT NULL OR Csi.Cause_Id IS NOT NULL;
相关问题