使用CASE进行MYSQL LEFT JOIN优化

时间:2012-03-17 12:28:29

标签: mysql optimization join case

我花了一些时间尝试使用CASE来处理这个SELECT但是我失败了......(感谢我现在正在使用COLASCE())

如何使用CASE / IF句子优化此SELECT?这是从字段选择的不同表中查询的快速方法吗?

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

3 个答案:

答案 0 :(得分:1)

在您的情况下使用case语句不会使查询更快,但是因为您要求它,下面是它的样子。

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

如果每个t_files,t_links等表都有folder_id字段,我也会尝试在这些表上执行UNION,然后使用t_folders将结果连接起来以获取folderid和foldername。

答案 1 :(得分:0)

连接必须以这种方式完成,因为它来自不同的表。您不能使用CASE来切换查询来自哪个表:必须先解析语句,包括其数据源,然后才能进行比较。

更重要的是,CASE返回值,而表名是..我不知道技术术语..查询的结构组件。这与你不能选择表格“Cool_Stuff”的原因相同:

select * from "Cool_" + "Stuff"

希望这能回答你的问题!

答案 2 :(得分:0)

您可以执行以下操作

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

FROM t_folders a
WHERE a.folderid = $folderId
ORDER BY a.folderid DESC ) master
LEFT JOIN t_files b
ON master.contenttype = 'file' AND master.contentid = b.fileid
LEFT JOIN t_links c
ON master.contenttype = 'link' AND master.contentid = c.linkid
 LEFT JOIN t_extfiles d
 ON master.contenttype = 'extfile' AND master.contentid = d.extfileid
 LEFT JOIN t_videos e
ON master.contenttype = 'video' AND master.contentid = e.videoid
LEFT JOIN t_exams f
ON master.contenttype = 'exam' AND master.contentid = f.examid

在最小化表a的结果时,可以选择联接操作

相关问题