2012-03-17 180 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