mysql
的数据通过WHERE
查询只能操作mysql
数据库存储上的sql
数据。当查询结果本身是筛选过的结果集
,那么我们就不能用where
继续操作结果集上的一些别名查询
所以mysql
有一个处理结果集的关键字 having
继续处理结果集数据
如下goods表,我想知道我们店铺手机销售价比市场价低多少? 并且把差价在400以上的数据查询出来
| gid | g_name |shop_price|market_price|
|---------|-------- |----------|------------|
| 1 | 三星2019 | 11112 | 12111 |
|---------|-------- |----------|------------|
| 2 | ipone8 | 6668 | 6999 |
|---------|-------- |----------|------------|
| 3 | 华为Note | 6666 | 7100 |
- 普通查询方式
SELECT gid,g_name,market_price,shop_price,market_price-shop_price FROM goods WHERE market_price-shop_price>400
| gid | g_name |shop_price|market_price|market_price-shop_price|
|---------|-------- |----------|------------|-----------------------|
| 1 | 三星2019 | 11112 | 12111 | 999 |
|---------|-------- |----------|------------|-----------------------|
| 3 | 华为Note | 6666 | 7100 | 434 |
如果我们不想二次使用这种长字段的方式查询数据
- 用
having
来筛选结果集
注:如果语句中使用WHERE
要把having
放在WHERE
后面
SELECT gid,g_name,market_price,shop_price,(market_price-shop_price) as diff FROM `collector_v` having diff>400
查询结果如下:
| gid | g_name |shop_price|market_price| diff |
|---------|-------- |----------|------------|-----------------------|
| 1 | 三星2019 | 11112 | 12111 | 999 |
|---------|-------- |----------|------------|-----------------------|
| 3 | 华为Note | 6666 | 7100 | 434 |