mysql case join,使用CASE进行MYSQL LEFT JOIN优化

I spent some time trying to get working this SELECT with CASE but I failed... (thank to that I'm using COLASCE() now)

How could I optimize this SELECT by using CASE/IF sentences? Is this a fast way to query from different tables selected by a field?

SELECT a.folderid, a.foldername, a.contenttype, COALESCE(b.descriptor, c.descriptor, d.descriptor, e.descriptor, f.descriptor) as descriptor

FROM t_folders a

LEFT JOIN t_files b

ON a.contenttype = 'file' AND a.contentid = b.fileid

LEFT JOIN t_links c

ON a.contenttype = 'link' AND a.contentid = c.linkid

LEFT JOIN t_extfiles d

ON a.contenttype = 'extfile' AND a.contentid = d.extfileid

LEFT JOIN t_videos e

ON a.contenttype = 'video' AND a.contentid = e.videoid

LEFT JOIN t_exams f

ON a.contenttype = 'exam' AND a.contentid = f.examid

WHERE a.folderid = $folderId

ORDER BY a.folderid DESC

解决方案

Using case statement will not make the query faster in your case, but since you asked for it, below is how it would look like.

SELECT a.folderid, a.foldername, a.contenttype,

(CASE a.contenttype

WHEN 'file' THEN b.descriptor

WHEN 'link' THEN c.descriptor

WHEN 'extfile' THEN d.descriptor

WHEN 'video' THEN e.descriptor

ELSE f.descriptor

END CASE) AS descriptor

FROM t_folders a

LEFT JOIN t_files b ON a.contenttype = 'file' AND a.contentid = b.fileid

LEFT JOIN t_links c ON a.contenttype = 'link' AND a.contentid = c.linkid

LEFT JOIN t_extfiles d ON a.contenttype = 'extfile' AND a.contentid = d.extfileid

LEFT JOIN t_videos e ON a.contenttype = 'video' AND a.contentid = e.videoid

LEFT JOIN t_exams f ON a.contenttype = 'exam' AND a.contentid = f.examid

WHERE a.folderid = $folderId

ORDER BY a.folderid DESC

If each of the t_files, t_links, etc tables has the folder_id field, I would also try doing a UNION on these tables and then left join the result with t_folders to get the folderid and foldername.

MySQL中的left join是一种连接查询的方式,它可以根据左表中的记录来关联右表中的记录。left join通常用于行记录信息补全,将子查询转换为一个大查询,将多个case查询转换为一个查询等。与left join相关的一些重要知识点包括:left join的语法、工作原理和应用场景。 left join的语法是通过在FROM子句中使用LEFT JOIN关键字,并指定左表和右表以及它们之间的连接条件。左表中的所有记录都会出现在结果集中,而右表中没有匹配的记录则会用NULL值填充。这样可以方便地将两个表中的数据进行关联查询。 left join的工作原理是先将左表和右表进行笛卡尔积,然后根据连接条件筛选出符合条件的结果。left join会将左表中的所有记录都保留在结果集中,而右表中没有匹配的记录则用NULL值填充。这就是为什么left join通常用于行记录信息补全的原因,可以确保左表中的所有记录都会出现在结果中。 left join的应用场景包括但不限于:行记录信息补全、将子查询转换为一个大查询、将多个case查询转换为一个查询等。通过合理使用left join,可以大大提高SQL性能,降低编程复杂度。 总的来说,left join是一种常用的连接查询方式,它可以根据左表中的记录来关联右表中的记录,并且可以用于行记录信息补全等应用场景。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值