2012-03-17 111 views
3

我花了一些时间试图让这个工作用SELECT CASE,但我失败了......(感谢给我使用COLASCE()现在)MYSQL LEFT JOIN优化与CASE

我如何能优化这个SELECT通过使用CASE/IF语句?这是从字段选择的不同表格快速查询的方式吗?

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 
+0

你想达到什么目的?为什么使用CASE或IF?你想优化什么?你明白什么是联盟?如果是的话,为什么它不是你要找的? – fancyPants 2012-03-17 13:43:34

+0

我想知道是否有可能替换这些LEFT JOINs CASE/IF。它可以更快的MySQL? – kbitdn 2012-03-18 11:39:02

+0

@tombom和kbitdn:我没有这个问题的答案,但我也会对它感兴趣...我也有类似的问题... – Chris 2012-03-28 12:11:28

回答

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和文件夹名的结果。

0

连接必须以这种方式完成,因为不同的表出来了。您不能使用CASE来切换查询出来的表:在有值进行比较之前,必须先解析语句,包括其数据源。

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

select * from "Cool_" + "Stuff" 

希望这回答你的问题!

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 

同时尽量减少对表中的结果,加入操作可以optmizsed