对非规范化表的SQL查询



我有下面提到的两个不带任何数据约束的非规范化表。Records_audit不会有重复的基于audit_id的行,尽管表并没有任何约束。

我将需要SQL查询从第二个表中提取具有附加匹配列refgroup_Name的records_audit的所有字段,使用两个表中AuditID的匹配条件,printedCount大于1,R_status为'Y'。我尝试使用左联接,但它正在选择所有记录。

你能帮我更正一下我的疑问吗?我尝试了下面的查询,但它从第二个表中选择了所有不需要的:

SELECT a.*, d.refgroup_Name 
from Records_audit a  
left join Patients_audit d ON ( (a.AUDITID=d.AUDITID ) 
and (a.printedCount> 1) 
AND (a.R_status='Y')
)  
ORDER BY 3 DESC

记录_审计:

>tr>y123>td style="ext-align:center;">aesop96><1>
AuditIDrecord_idcreated_d_t打印计数
1Img778622020-02-01 08:40:12.6142Img879622021-02-01 08:40:12.614Y

left join将为您提供"左";表,即from表。由于您没有where子句来约束查询,因此您将获得Records_audit中的所有记录。

有关联接的详细信息,请参见SQL联接的可视化表示。

如果您的目的是获取Records_audit中R_status为YprintedCount > 1的所有记录,请将它们放入where子句中。

select ra.*, pa.refgroup_name 
from records_audit ra  
left join patients_audit pa on ra.auditId = pa.auditId
where ra.printedCount > 1
and ra.r_status = 'Y'
order by ra.created_d_t desc

这将匹配Records_audit中与where子句匹配的所有记录。left join确保它们匹配,即使它们没有匹配的Patients_audit记录。

其他注意事项:

  • 您的order by 3依赖于在Records_audit中声明列的顺序。如果您想通过records_audit.created_d_t订购,请写order by a.created_d_t
  • 如果您的查询对数据进行了假设,请添加一个约束以确保它为真并保持为真

最新更新