Mysql语句书写顺序:
select[distinct]
from
join(如left join)
on
where
group by
having
union
order by
limit
Mysq语句执行顺序
from
on
join
where
group by
having
select
distinct
union
order by
分析如下:
case 1:
``select a.Customer
from orders a
where a.Customer=‘xiaofeng’ or a.Customer = ‘xiaoxiao’ `
```
分析:首先是from语句找到表格,然后根据where得到符合条件的记录,最后select出需要的字段
case 2:
select a.Customer,sum(a.OrderPrice) from orders a where a.Customer='xiaoxiao' or a.Customer = 'xiaofeng' group by a.Customer
分析:在from,where执行后,执行group by,同时也根据group by的字段,执行sum这个聚合函数。
case 3:
select a.Customer,sum(a.OrderPrice) from orders a where a.Customer='xiaofeng' or a.Customer = 'xiaofeng' group by a.Customer having sum(a.OrderPrice) > 2000
分析:由于where是在group之前执行,那么如何对group by的结果进行筛选,就用到了having,having就是对分组的筛选条件。
case 4:
select distinct sum(a.OrderPrice) As order1,sum(d.OrderPrice) As order2 from orders a left join (select c.* from Orders c) d on a.O_Id = d.O_Id where a.Customer='xiaofeng' or a.Customer = 'xiaoxiao'
分析:在执行from关键字之后根据on指定的条件,把left join指定的表格数据附在from指定的表格后面,然后再执行where字句。
总结:
1、使用distinct要写在所有要查询字段的前面,后面有几个字段,就代表修饰几个字段,而不是紧随distinct的字段;
2、group by执行后(有聚合函数),group by后面的字段在结果中一定是唯一的,也就不需要针对这个字段用distinct;