加入收藏 | 设为首页 | 会员中心 | 我要投稿 拼字网 - 核心网 (https://www.hexinwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

MySQL中的LEFT OUTER JOIN vs SUBSELECT

发布时间:2021-03-06 16:03:51 所属栏目:MySql教程 来源:网络整理
导读:我有一个表table1,其中有3列column1,column2和column3. column1和column2是一个带有2个其他表的FOREIGN KEY.但是,第3列中的数据来自n个表. 对于例如让我们考虑一下Facebook.要显示活动,它可能会维护一个表,该表可能具有user1 photoliked photo1或user1 statu

我有一个表table1,其中有3列column1,column2和column3.

column1和column2是一个带有2个其他表的FOREIGN KEY.但是,第3列中的数据来自n个表.

对于例如让我们考虑一下Facebook.要显示活动,它可能会维护一个表,该表可能具有user1 photoliked photo1或user1 statusliked status1.所以在这种情况下,column3不能是具有特定表的FOREIGN KEY.

现在有两种获取真实数据的方法 –

第一路 –

SELECT user_id,verb_id,CASE WHEN verb_id = photoliked THEN
            (SELECT photo_name FROM photos WHERE photo_id = column3) -- getting the desired data from the third column
         WHEN verb_id = statusliked THEN
            (SELECT status FROM statustable WHERE status_id = column3) 
         ELSE '' END AS performedon
FROM table1
     JOIN table2 ON user_id = user_id  -- joining the first column
     JOIN table3 ON verb_id = verb_id  -- joining the second column

第二路 –

SELECT user_id,CASE WHEN verb_id = photoliked THEN
            p.photo_name
         WHEN verb_id = statusliked THEN
            s.status
         ELSE '' END AS performedon
FROM table1
     JOIN table2 ON user_id = user_id  -- joining the first column
     JOIN table3 ON verb_id = verb_id  -- joining the second column
     LEFT JOIN photos p ON p.photo_id = column3  -- joining the column3 with specific table 
     LEFT JOIN statustable s ON s.status_id = column3

检索数据的两种方法中哪一种更好?
哪两个查询更便宜? 最佳答案 第二个会更快,原因是第一个包含所谓的相关子查询.子查询与主查询中的记录具有相关性.因此,子查询需要为主查询中的每个匹配记录运行一次.在您的情况下,它不能运行子查询,直到它确定主查询中的verb_id的值.这是很多查询要运行.

对第一个查询的EXPLAIN应指出此问题.当你在EXPLAIN中看到它时,它通常是一个红旗.

(编辑:拼字网 - 核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!