MySQL必知必會筆記(十四) 組合查詢

2021-09-26 05:37:06 字數 1207 閱讀 4145

可union操作符來組合數條sql語句。

union的使用很簡單,所需做的只是給出每條select語句,在各條語句之間放上關鍵字union。

輸入select vend_id,prod_id,prod_price from products where prod_price <= 5 union select vend_id,prod_id,prod_price from products where vend_id in (1001,1002);

輸出

第一條select檢索不高於5的所有物品,第二條select使用in找出**商1001和1002生產的所有物品。union指示mysql執行兩條select語句,並把輸出組合成單個查詢結果集。

如果分別執行以上兩條select語句,那麼第一條select返回4行,第二條返回5行,但是使用union組合了兩條select語句之後,只返回了8行而不是9行。這是union的預設行為,但是如果需要,也可以改變:使用union all,而不是union。

輸入select vend_id,prod_id,prod_price from products where prod_price <= 5 union all select vend_id,prod_id,prod_price from products where vend_id in (1001,1002);

輸出

使用union all,mysql不取消重複的行,因此這裡出現了9行。

在用union組合查詢時,只能使用一條order by子句,它必須出現在最後一條select語句之後。

輸入select vend_id,prod_id,prod_price from products where prod_price <= 5 union select vend_id,prod_id,prod_price from products where vend_id in (1001,1002) order by vend_id,prod_price;

輸出

MySQL必知必會 十四 組合查詢

開始線 mysql也允許執行多個查詢,並將結果作為單個查詢結果集返回,這些組合查詢通常稱為並或復合查詢 有兩種基本情況,其中需要使用組合查詢 1.在單個查詢中從不同的表返回類似結構的資料 2.對單個表執行多個查詢,按單個查詢返回資料 可用union操作符來組合數條sql查詢 查詢 小於等於5的所有物...

mysql必知必會 mysql必知必會(四)

十四 理解子查詢 1 通過子查詢過濾 這本書在所有的章節都關連到了資料庫表,訂單資料是儲存在兩個表中,orders表儲存著 訂單號碼 顧客id和訂單日期。個人的訂單列表關連著orderitems表,訂單表沒有儲存顧客資訊,它只是儲存著顧客id,這實際的顧客資訊是儲存在customers表中。現在假設...

MySQL必知必會十七 組合查詢

mysql允許執行多個查詢 多條select語句 並將結果作為單個查詢結果集返回。這些組合查詢通常稱為並 union 或復合查詢 compound query 有兩種基本情況,其中需要使用組合查詢 mysql select vend id,prod id,prod price from produc...