我有下面提到的两个不带任何数据约束的非规范化表。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
记录_审计:
AuditID | record_id | created_d_t | >打印计数 | |||
---|---|---|---|---|---|---|
1 | Img77862 | 2020-02-01 08:40:12.614 | tr>2 | Img87962 | 2021-02-01 08:40:12.614 | y123>td style="ext-align:center;">aesop96>Y | <1>
left join
将为您提供"左";表,即from
表。由于您没有where
子句来约束查询,因此您将获得Records_audit
中的所有记录。
有关联接的详细信息,请参见SQL联接的可视化表示。
如果您的目的是获取Records_audit
中R_status为Y
和printedCount > 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
- 如果您的查询对数据进行了假设,请添加一个约束以确保它为真并保持为真