【问题标题】:Need help creating this SELECT procedure需要帮助创建此 SELECT 过程
【发布时间】:2020-07-13 07:07:02
【问题描述】:

我有三个表格,分别是 Complaint、ComplaintDetail 和 Person。

create table Complaint (
    id int identity(1,1) primary key,
    complaintName varchar(50),
    datetime datetime,
    place nvarchar(MAX),
    declarantName nvarchar(50),
    detail nvarchar(MAX),
    verifyStatus bit   /* approved or not */
)
go

create table ComplaintDetail (
    id int identity(1,1) primary key,
    personId int,
    constraint cdp foreign key (personId) references Person(id),
    compId int,
    constraint cpc foreign key (compId) references Complaint(id),
    crimeType nvarchar(50)
)
go

create table Person (
    id int primary key,
    name nvarchar(50),
    gender bit NOT NULL,
    dob date,
    address nvarchar(MAX),
    image varchar(100),
    nationality varchar(50),
    job varchar(20),
    alive bit DEFAULT 1
)

我想创建一个 SELECT 程序来查找所有与该 Person.id 链接的投诉

我尝试了类似的方法,但它不起作用。

CREATE PROC findExcludedComplaints
    @personID int
AS
BEGIN
    SELECT * FROM Complaint
    INNER JOIN ComplaintDetail ON Complaint.id = ComplaintDetail.compId
    INNER JOIN Person ON ComplaintDetail.personId != Person.id
    WHERE Person.id = @personID
END
GO

【问题讨论】:

  • 请比“它不起作用”更具体

标签: sql sql-server sql-server-2014


【解决方案1】:

要得到你想要的,你可以像这样在 Person 和 ComplaintDetail 上使用LEFT JOIN

LEFT JOIN Person ON ComplaintDetail.personId = Person.id

并将WHERE 修改为

AND ComplaintDetail.personId IS NULL

【讨论】:

  • 请注意,条件 Person.id = @personID 需要在左连接中,而不是在 where 子句中,此选项才能按预期工作。
【解决方案2】:

据我所知,有两种方法可以阅读您的问题。您现有的查询对于其中一个是正确的。

第一种解释是:“获取与@personId参数匹配的人的所有信息,并从投诉和投诉详细信息中找到与该人无关的所有列值。”

第二种解释是:“给我所有与@personId 无关的投诉,并让我获得与该投诉相关的人的详细信息

所以区别在于您从person 表中获得的值:匹配@personId 的人的值,与实际与投诉相关但不匹配@personId 的人的值.

您现有的查询将正确地为您提供第一个结果,所以我猜您不希望这样。所以我推断你一定想要第二个结果。那将是:

select  * -- you shouldn't really use select *
from    Person            p
join    ComplaintDetails  d on d.personId = p.id
join    Complaints        c on c.id = d.compId
where   p.id != @personId

【讨论】:

    【解决方案3】:

    我想创建一个 SELECT 程序来查找所有不与该 Person.id 链接的投诉

    使用cross join 生成人员和投诉的所有组合。然后过滤掉那些存在的:

    select p.*, c.*
    from persons p cross join
         complaints c left join
         complaintdetail cd
         on cd.person_id = p.id and cd.complaint_id = c.id
    where cd.id is null;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-06
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2013-12-08
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多