SQL學習 組合查詢

2021-09-13 10:12:45 字數 1917 閱讀 6456

多數sql查詢都只包含乙個或從多個表中返回資料的單條select語句。mysql也允許執行多個查詢(多條select語句),並將結果作為單個查詢結果集返回。這些組合查詢通常稱為復合查詢

有兩種情況需要使用組合查詢:

可用union操作符來組合數條sql查詢。利用union,可給出多條select語句,將它們的結果組合成單個結果集。

假如需要**小於等於5的所有物品的乙個列表,而且還想包括**商1001和1002生產的所有物品(不考慮**)。

mysql> 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);

+---------+---------+------------+

| vend_id | prod_id | prod_price |

+---------+---------+------------+

| 1003 | fc | 2.50 |

| 1002 | fu1 | 3.42 |

| 1003 | sling | 4.49 |

| 1003 | tnt1 | 2.50 |

| 1001 | anv01 | 5.99 |

| 1001 | anv02 | 9.99 |

| 1001 | anv03 | 14.99 |

| 1002 | ol1 | 8.99 |

+---------+---------+------------+

8 rows in set (0.00 sec)

如果想返回所有匹配的行,可使用union all。

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

mysql> 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;

+---------+---------+------------+

| vend_id | prod_id | prod_price |

+---------+---------+------------+

| 1001 | anv01 | 5.99 |

| 1001 | anv02 | 9.99 |

| 1001 | anv03 | 14.99 |

| 1002 | fu1 | 3.42 |

| 1002 | ol1 | 8.99 |

| 1003 | fc | 2.50 |

| 1003 | tnt1 | 2.50 |

| 1003 | sling | 4.49 |

+---------+---------+------------+

8 rows in set (0.02 sec)

SQL 組合查詢

如何利用union操作符將多條select語句組合成乙個結果集?sql允許執行多個查詢 多條select語句 並將結果作為乙個查詢結果集返回。這些組合查詢通常稱為並 union 或復合查詢 compound query 主要有兩種情況需要使用組合查詢 在乙個查詢中從不同的表返回結構資料 對乙個表執行...

sql模糊查詢實現組合查詢

資料庫程式設計中經常遇到組合查詢的情況。例如,某公司資料庫裡有一張存放使用者資訊的表user info,它有多個字段 userid,id,name,age,address。其中userid是表的主碼,表示使用者的使用者號,該使用者號對每個使用者都是唯一的 id表示使用者省份證號。此時要對使用者資訊進...

SQL 子查詢與組合查詢

2.組合查詢 union union all 在 where 條件中某個值可以通知子查詢句表示 就是 select 鑲嵌select 語句select from table1 where id select id from table2 where name xx with as 相當於將 as 內...