1.sql in和exists
in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询。一直以来认为exists比in效率高的说法是不准确的。如果查询的两个表大小相当,那么用in和exists差别不大。
全文:in和exists
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in
例如:表A(小表),表B(大表)
1:select*from Awhere ccin (select ccfrom B)效率低,用到了A表上cc列的索引;
select *from Awhere exists(select ccfrom Bwhere cc=A.cc)效率高,用到了B表上cc列的索引。
相反的
2:select*from Bwhere ccin (select ccfrom A)效率高,用到了B表上cc列的索引;
select *from Bwhere exists(select ccfrom Awhere cc=B.cc)效率低,用到了A表上cc列的索引。
not in 和not exists
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。
in 与 =的区别
select name from studentwhere namein ('zhang','wang','li','zhao');与
select namefrom studentwhere name='zhang'or name='li'or name='wang'or name='zhao'的结果是相同的。
2.left join 条件on与where
on中的条件关联,一表数据不满足条件时会显示空值。where则输出两表完全满足条件数据。我们知道标准查询关键字执行顺序为 from->where->group by->having->order by
left join 是在from范围类所以 先on条件筛选表,然后两表再做left join。 而对于where来说在left join结果再次筛选。
3.null值
Oracle
Oracle 没有 ISNULL() 函数。不过,我们可以使用 NVL() 函数达到相同的结果:
SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products
MySQL
MySQL 也拥有类似 ISNULL() 的函数。不过它的工作方式与微软的 ISNULL() 函数有点不同。
在 MySQL 中,我们可以使用 IFNULL() 函数,就像这样:
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
或者我们可以使用 COALESCE() 函数,就像这样:
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
on中的条件关联,一表数据不满足条件时会显示空值。where则输出两表完全满足条件数据。我们知道标准查询关键字执行顺序为 from->where->group by->having->order by left join 是在from范围类所以 先on条件筛选表,然后两表再做left join。 而对于where来说在left join结果再次筛选。
3.null值
5万+

被折叠的 条评论
为什么被折叠?



