MYSQL LEFT JOIN 优化与 CASE

标签 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

最佳答案

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

相关文章:

MySQL单字段斜率(趋势)(最佳拟合线)

php - 获取所有数据并删除表的重复项

mysql - 从具有相同 id 的多个表中检索数据

mysql - 在workbench中升级mysql版本

mysql - 替代包含 max() 和 GROUP BY 的自连接以提高性能

java - 如何改善应用程序的 ActivityManager 加载时间?

optimization - 是否有可能/使用卫生宏进行编译时计算优化的例子是什么?

java - 忙碌的等待, sleep 和准确性

sql - 使用 Lambda 表达式以及 Join、GroupBy、Count 和 Sum 的 Linq to SQL

php - 在 Doctrine 2 中加入查询实体