學習資料庫筆記五,資料庫筆記

來源:互聯網
上載者:User

學習資料庫筆記五,資料庫筆記

where 型子查詢

內層查詢結果充當外層查詢條件


1.查詢最新的商品

   步驟a ) select max(goods_id) from goods;  這是一條動態語句,怎麼添加都會是最新的,它查出了最新的一列goods_id

   步驟b ) 查詢最新的商品的整行資訊,需要拿上面的語句作為條件

                select goods_id,goods_name from goods where goods_id = (select max(goods_id) from goods);

   步驟c ) 現在的結果就是"goods_id"為最新的那行的記錄


*遇到問題要會分解,一步步做就能解出


2.查詢出每個欄目下最新的商品

   步驟a ) select max(goods_id) from goods group by cat_id;  查出每個欄目下最新的商品ID

   步驟b ) 以上面查出的id為條件,接著查

                 select * from goods where goods_id in (select max(goods_id) from goods group by cat_id);    要用In,因為不只一個條件





from型子查詢

查詢出的結果集可以當成一張表來看

平時我們from後跟的都是一張表,from型子查詢這種情況,可以把整個查詢當成一張表

(通常我們查詢出的結果只是在記憶體中的一個結果集,而非在硬碟上的內容,可以用having來查詢出它)


一條查詢語句,用括弧括住,起個別名,它就成為一張“新”的暫存資料表了,如

(select * from goods order by cat_id asc,goods_id desc)  as temp 這樣就把查詢結果變成了新的temp表  這個技巧很有用!


用這個暫存資料表時,

select goods_id,cat_id,goods_name from (select * from goods order by cat_id asc,goods_id desc) as temp  group by cat_id;


暫存資料表只需要在你的select語句外加括弧,寫個as和表名,一定要記住上面這樣的寫法,非常有用。







相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.