具有特定条件的左连接请帮忙

发布于 2024-12-16 23:36:46 字数 875 浏览 0 评论 0原文

构建查询时遇到问题 这是简化的表结构 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瘫痪情歌 2024-12-23 23:36:46
SELECT e.id, e.name, f.file_id AS file_id, f.path
FROM event e
LEFT JOIN
(
    SELECT ef.event_id, uf.id AS file_id, uf.path
    FROM event_file ef
    INNER JOIN uploaded_file uf ON ef.file_id = uf.id AND uf.type = 2
) f ON f.event_id = e.id

这应该可以(未经测试。)
您获得空记录的原因是您仅在 uploaded_file 表上指定 uf.type 条件,这不会对 event_file 的左连接施加任何影响。

SELECT e.id, e.name, f.file_id AS file_id, f.path
FROM event e
LEFT JOIN
(
    SELECT ef.event_id, uf.id AS file_id, uf.path
    FROM event_file ef
    INNER JOIN uploaded_file uf ON ef.file_id = uf.id AND uf.type = 2
) f ON f.event_id = e.id

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文