select * from test where A='a' or B ='b' 跟 select * from test where A='a' union all select * from test where B='b' ------------ 是不等价的。例如:你一行中A='a',同时B='b',使用or只会出来一行,使用Union ALL就是两行。 改成: select * from test where A='a' union select * from test where B='b' 默认情况下,UNION 运算符将从结果集中删除重复的行。如果使用 ALL 关键字,那么结果中将包含所有行而不删除重复的行。
A='a' or B='b' 如果同时满足A='a' 且 B='b'的记录 where A='a' or B='b'只会出现一条 union all则会出现重复的2条 应该使用union
select * from test where A='a' or B ='b' 等于是 select * from test where A='a' 的记录 + select * from test where B ='b' 的记录 2者出来的记录不是按照先排a的或者先排b的,很可能是交叉排序出现的,所以分开做索引是不起作用的!
UNION ALL
select * from test where B ='b' 改成这样分开建立
select * from test where A='a'
union all
select * from test where B='b'
会失效的
直接用or
或者是
select * from test where A='a'
union all
select * from test where B='b'
跟
SQL code---改成这样 再建立索引
select * from test where A='a'
union all
select * from test where B='b' 根本就不等价
说不等价是不是因为用的union all?是应该用union么,还是其他原因,能解释下么
a='a' or b='b' 会分别走索引,之后组成一个table,再去和原表进行一个主键的Nested Loop,取出*.
等介于union (非union all)union 相当于每个走索引,然后和原表进行一个主键的Nested Loop,取出*.两个结果再组成一个table.
跟
select * from test where A='a'
union all
select * from test where B='b'
------------
是不等价的。例如:你一行中A='a',同时B='b',使用or只会出来一行,使用Union ALL就是两行。
改成:
select * from test where A='a'
union
select * from test where B='b'
默认情况下,UNION 运算符将从结果集中删除重复的行。如果使用 ALL 关键字,那么结果中将包含所有行而不删除重复的行。
如果同时满足A='a' 且 B='b'的记录
where A='a' or B='b'只会出现一条
union all则会出现重复的2条
应该使用union
等于是
select * from test where A='a' 的记录 + select * from test where B ='b' 的记录
2者出来的记录不是按照先排a的或者先排b的,很可能是交叉排序出现的,所以分开做索引是不起作用的!