以下2个查询之间有什么区别? (它们都产生相同的结果)
select *
from (
select * from (
select *
from phppos_items
where name like 'AB10LA2%' and deleted = 0
order by `name` limit 16
) t
union
select * from (
select *
from phppos_items
where item_number like 'AB10LA2%' and deleted = 0
order by `name` limit 16
) t
union
select * from (
select *
from phppos_items
where category like 'AB10LA2%' and deleted = 0
order by `name` limit 16
) t
) as top_rows
order by `name` limit 16
VS
select *
from (
(select *
from phppos_items
where name like 'AB10LA2%' and deleted = 0
order by `name` limit 16)
union
(select *
from phppos_items
where item_number like 'AB10LA2%' and deleted = 0
order by `name` limit 16)
union
(select *
from phppos_items
where category like 'AB10LA2%' and deleted = 0
order by `name` limit 16)
) as top_rows
order by `name` limit 16
答案 0 :(得分:3)
第一个版本有另一组临时表,在这种特定情况下没用,浪费资源 以下所有内容都会产生相同的结果:
SELECT * FROM T1;
SELECT * FROM (SELECT * FROM T1);
SELECT * FROM (SELECT * FROM (SELECT * FROM T1));
...
...
到无穷大: - )
在你的具体案例中,这就足够了:
select *
from phppos_items
where
(name like 'AB10LA2%' OR item_number like 'AB10LA2%' OR category like 'AB10LA2%')
and deleted = 0
order by `name` limit 16
答案 1 :(得分:0)
第一个查询会嵌入一组额外的SELECT * FROM (sub-query)
。优化器需要稍微长一点才能对其进行排序。
从功能上讲,查询之间没有真正的区别。第二个更简单,因此更可取。
答案 2 :(得分:0)
我看到的唯一区别是在顶部,UNION
的子查询组件被命名。显然,由于第二个版本没有错误,MySQL在这种结构中不需要子查询名称。顺便说一句,你是否测试过这个版本比使用OR
的相应单个查询更快?