我正在尝试更正此查询,我需要首先加入表格capcase,然后加入名为capstatus second的表格。从capcase状态和capcaseservicesprovidedstatus有不同的表格,其中可以看到外键,我需要加入正确的表。我想知道是否可能需要使用除“内连接”之外的连接来完成此任务或确认我的查询错误,因为最后两行是我认为存在的问题。如有任何帮助,请提前感谢。
SELECT family.Id as Family_ID, person.firstName + ' ' + person.lastName as Name, capcaseServicesProvided.idperson as Person_ID,capcaseservicesProvided.idCase as Case_ID, capcaseServicesProvided.Id as Service_ID,capStatus.Status as Case_Status, capServices.Service, capStatusService.ServiceStatus as Service_Status,
capcaseServicesProvided.Qty, capServicesUnit.Unit, capcaseServicesProvided.Date as Service_Date, capCase.DateApplied as Case_Date
FROM capcaseServicesProvided
INNER JOIN person on capcaseServicesProvided.idperson = person.Id
INNER JOIN capServices on capcaseServicesProvided.idService = capServices.Id
INNER JOIN capServicesUnit on capcaseServicesProvided.Unit = capServicesUnit.Id
INNER JOIN capStatusService on capcaseServicesProvided.Status = capStatusService.Id
INNER JOIN family on person.idFamily = family.Id
INNER JOIN capStatus on capcaseServicesProvided.Status= capStatus.Id
INNER JOIN capCase on capCaseServicesProvided.Date = capCase.DateApplied;
答案 0 :(得分:1)
我想建议一种方法,而不是尝试一种特定的解决方案。请注意,我们对您的表格或其设计一无所知,因此要求我们理解要么需要相当多的信息,所以最终您最好了解JOINS和/或如何自己解决这些困境。
我建议你将初始查询的大小减少到ABSOLUTE MINIMUM,看起来(我认为)是这样的:
SELECT
family.Id AS Family_ID
, person.firstName + ' ' + person.lastName AS Name
, capcaseServicesProvided.idperson AS Person_ID
, capcaseservicesProvided.idCase AS Case_ID
, capcaseServicesProvided.Id AS Service_ID
FROM capcaseServicesProvided
INNER JOIN person ON capcaseServicesProvided.idperson = person.Id
INNER JOIN family ON person.idFamily = family.Id
;
现在假设最小查询是正确的,尝试加入ONE EXTRA TABLE并将其中所需的列包含在select子句中。首先使用INNER JOIN添加额外的表。如果您注意到某些行要消失,则将其更改为LEFT JOIN
e.g。
SELECT
family.Id AS Family_ID
, person.firstName + ' ' + person.lastName AS Name
, capcaseServicesProvided.idperson AS Person_ID
, capcaseservicesProvided.idCase AS Case_ID
, capcaseServicesProvided.Id AS Service_ID
, capServices.Service
FROM capcaseServicesProvided
INNER JOIN person ON capcaseServicesProvided.idperson = person.Id
INNER JOIN family ON person.idFamily = family.Id
INNER JOIN capServices ON capcaseServicesProvided.idService = capServices.Id
-- or if needed --LEFT JOIN capServices ON capcaseServicesProvided.idService = capServices.Id
;
继续重复此循环,直到您加入所有需要的表格。
我怀疑你只需要一个或多个LEFT JOINS但没有来自每个表的样本数据和每个表的DDL,很难告诉你哪些表需要这些。