gpt4 book ai didi

MYSQL LEFT JOIN 优化与 CASE

转载 作者:可可西里 更新时间:2023-11-01 08:53:01 26 4
gpt4 key购买 nike

我花了一些时间尝试使用 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

最佳答案

在您的案例中使用 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。

关于MYSQL LEFT JOIN 优化与 CASE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com