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

MySQL中的LEFT OUTER JOIN vs SUBSELECT

发布时间:2021-03-06 12:44:27 所属栏目:编程 来源:网络整理
导读:我有一个表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中看到它时,它凡是是一个红旗.

(编辑:湖南网)

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

    热点阅读