mysql表複製與子查詢

2021-09-23 07:39:32 字數 1039 閱讀 9191

mysql表複製與子查詢

1、複製表

create table g2 like goods;
g2和goods表頭都一樣,但無內容

insert into g2 select *from goods order by cat_id asc,shop_price desc;
將goods表按cat_id公升序、shop_price降序匯入到g2表中(無效,還是goods表中原來的順序)

truncate g2;
清空g2表

2、子查詢

where型、from型、exists型

where型:把內層的查詢結果作為外層查詢的比較條件

例:查詢每個欄目下最貴的商品

select goods_id, cat_id, goods_name, shop_price from goods where shop_price in (select max(shop_price) from goods group by cat_id);
from型:把內層的查詢結果當成臨時表(必須有別名,即加 as 臨時表名),共外層sql再次查詢

例:查詢每個欄目下最貴的商品

select * from (select goods_id, cat_id, goods_name, shop_price from goods order by cat_id, goods_id desc) as tmp group by cat_id;
exist型:把外層的查詢結果拿到內層,看內層查詢是否成立

例:查有商品的欄目(典型)

select select cat_id, cat_name, from category where exists (select * from goods where goods.cat_id=category.cat_id);
category.cat_id為外層查詢結果,它帶入內層select;

MySQL子查詢,聯結表

子查詢 select cust id from orders where order num in select order num from orderitems where prod id tnt2 對每個客戶執行count 計算,應該將count 作為乙個子查詢 select cust nam...

MySQL子查詢與多表查詢

1 什麼是子查詢 查詢中的查詢即為子查詢,一般使用括號將子查詢sql括起來,如下sql語句 select from select from user info users2 什麼時候用子查詢 當在查詢過程中需要知道乙個已知量的不確定資料時使用子查詢。select from address where...

MySQL多表查詢與子查詢

多表查詢 多表查詢實際上根據查詢要求先將兩個表連線起來,形成一張新錶,再在新錶中查詢出滿足條件的記錄多表查詢可分為連線查詢和子查詢。一 連線查詢 可分為外連線和內連線 關於外鏈結的幾點說明 a 左外連線包括兩個表中滿足條件的行,再加上在join子句中指出的左表中不滿足的行。b 不滿足鏈結條件的行在結...