欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL查詢結果處理方式

 更新時間:2024年04月10日 09:32:47   作者:Q小白養(yǎng)成記  
這篇文章主要介紹了MySQL查詢結果處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

SELECT 表頭名 FROM 庫名.表名 [WHERE條件] 分組 | 過濾 ;

分組 

select列名 count(*)from 表名 group by 列名 條件;

group By注意事項:

  • 1.可以使用單個列,多個列組合,甚至是對列的計算結果
  • 2.分組的依據(jù)必須是可以從數(shù)據(jù)表中獲得的數(shù)據(jù)
  • 3.分組之后是針對子表數(shù)據(jù)進行操作,不會在顯示單行數(shù)據(jù)等,或者說不能完整的查看單個子表的數(shù)據(jù)
  • 4. select后面除了聚合函數(shù)處理的部分外,最好選取的列都出現(xiàn)在group by子句中
  • 5.NULL 空也會被歸類為一種值,所有NULL 的行被分到一張子表中
  • 6.group by出現(xiàn)在where 后,order by 前面

過濾

select 表頭名  from 庫.表  where 篩選條件  having   篩選條件;

select列名 count(*)from 表名where 條件 group by 列名having 條件;

練習

1.orderltems表包含每個訂單的單獨項目,返回每個訂單號(order_num)的行數(shù)(作為order_lines),并按order_lines對結果排序

mysql> SELECT order_num, COUNT(*) AS order_lines  
    -> FROM orderitems  
    -> GROUP BY order_num  
    -> ORDER BY order_lines;
+-----------+-------------+
| order_num | order_lines |
+-----------+-------------+
|     20006 |           1 |
|     20007 |           1 |
|     20008 |           1 |
|     20005 |           4 |
|     20009 |           4 |
+-----------+-------------+
5 rows in set (0.01 sec)

2.返回一個名為cheapes_item的字段,其中包含每個供應商的最低成本項目(使用Producrs表中的prod-price),并將結果從最低成本到最高成本排序。

mysql> SELECT vend_id, MIN(prod_price) AS cheapest_item
    -> FROM products
    -> GROUP BY vend_id
    -> ORDER BY cheapest_item ASC;
+---------+---------------+
| vend_id | cheapest_item |
+---------+---------------+
|    1003 |          2.50 |
|    1002 |          3.42 |
|    1001 |          5.99 |
|    1005 |         35.00 |
+---------+---------------+
4 rows in set (0.01 sec)

3.找到最好的客戶,為至少100項的每個訂單返回訂單號(orderlems表中的order num)。 

mysql> select order_num from orderitems
    -> group by order_num 
    -> having sum(quantity) >=100;
+-----------+
| order_num |
+-----------+
|     20007 |
+-----------+
1 row in set (0.00 sec)

4. 另一種確定最佳客戶的方法是根據(jù)他們花了多少錢。

編寫一條SQL語句,返回總價至少為1000的每個訂單的訂單號(0rderitems表中的order_num)。

這里有一個提示:對于這個,你需要計算并求和total(item_price乘以guantiy)。

按訂單號對結果進行排序。

mysql> select order_num from orderitems 
    -> group by order_num 
    -> having sum(item_price * quantity) >= 1000
    -> order by order_num;
+-----------+
| order_num |
+-----------+
|     20007 |
+-----------+
1 row in set (0.00 sec)

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論