具有特定条件的左连接请帮忙
构建查询时遇到问题 这是简化的表结构 3个表,
Event [Event_id , Event_name]
Event_files [Event_id(FK) , File_id(FK)]
Uploaded_Files[File_id , File_type, File_path]
我们主要有2种文件类型
image = 2
document = 4
我想做的是获取事件及其图像(如果他们有一个图像) 我试图用这个查询来做到这一点,
select e.id, e.name,uf.id as file_id,uf.path
from event e
left join event_file ef on ef.event_id = e.id
left join uploaded_file uf ON ef.file_id = uf.id
我知道我需要应用一个条件,但每次我在 where 或 ON 中执行时,查询总是有问题 例如,如果我申请:
left join uploaded_file uf ON ef.file_id = uf.id AND (uf.type = 2 )
它仍然会返回 2 条记录,其中包含图像和文件,其中一个记录的 file_path null 。
另一方面,如果我执行以下操作:
where (uf.id is null OR (uf.id is not null AND uf.type=2))
仅包含文件而没有图像的事件将不再返回,
请问有解决方案吗?
提前致谢
am having a problem constructing a query
here is simplified tables structure
3 tables
Event [Event_id , Event_name]
Event_files [Event_id(FK) , File_id(FK)]
Uploaded_Files[File_id , File_type, File_path]
we mainly have 2 file types
image = 2
document = 4
what am trying to do is to get the events along with their images (if they have an image )
am trying to do this with this Query
select e.id, e.name,uf.id as file_id,uf.path
from event e
left join event_file ef on ef.event_id = e.id
left join uploaded_file uf ON ef.file_id = uf.id
i know that i need to apply a condition but each time i do in the where or ON there is always problem with the Query
for example if i apply :
left join uploaded_file uf ON ef.file_id = uf.id AND (uf.type = 2 )
it will still return 2 records for the events that has both image and file one of them with file_path null .
on the other hand if i do the following :
where (uf.id is null OR (uf.id is not null AND uf.type=2))
the events with only files and no image will not be returned any more
is there is solution please ?
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以(未经测试。)
您获得空记录的原因是您仅在 uploaded_file 表上指定 uf.type 条件,这不会对 event_file 的左连接施加任何影响。
This should do (untested.)
The reason you're getting the empty record is because you only specify the uf.type condition on the uploaded_file table, which imposes nothing on the left join for event_file.