乙個簡單的Mysql的聯合查詢列子

2021-05-09 20:30:54 字數 1266 閱讀 4195

乙個mysql的聯合查詢列子,很基本的,不過很實用。

先看資料表。資料表class:

------------------------------- 

id   cname

-------------------------------

1    **

2    女皮褲

3    女彩棉

-------------------------------

class表存放的是產品的大類名稱和其序號

資料表product:

-------------------------------

pid   ptype   pparent

-------------------------------

1      a01      1

2      a21      1

3      b10      2

4      c11      3

5      c01      2

-------------------------------

product表存放的是產品名稱,和其所屬大類的id(pparent) 

現在要求顯示所有產品序號、名稱、所屬類別,如下形式:

-------------------------------

序號 名稱     類別

-------------------------------

1      a01      **

2      a21      **

3      b10      女皮褲

4      c11      女彩棉

5      c01      女皮褲

-------------------------------

這裡要查詢product表,根據pparent欄位再讀出對應的class表中pname欄位。最傳統的,可以用兩個select語句實現,但是mysql中有聯合查詢語句可以簡單的實現:

select product.*, class.* from product inner join class on product.pparent=class.id where product.pid is not null

在php中,通過這樣查詢出來的記錄都放在陣列裡面,比如:

$myrow=mysql_fetch_array(mysql_query($sql));

那麼$myrow陣列中,前面存放的是product中的字段,後面存放的是class的字段。

乙個多表聯合查詢引發的思考

朋友做乙個專案,遇到乙個多表聯合查詢的需求。需要乙個sql,當a表中system id值為123時,找到b表和c表的關聯,當b表滿足system id值為123時,包含其中的role id資料,顯示c表中name資料。例如查詢結果為 james lucy.t table a表 idsystem id...

乙個簡單的查詢語句

今天要寫乙個查詢語句,寫了半天沒弄出來,最後在同事的幫助下,用group by搞定了。其實蠻簡單的,只是我用資料庫用的太少了,呵呵 物品表 good 欄位為gid 物品id price 物品 和tid 所屬交易id 交易表 trade,欄位為tid 交易id date 交易時間 需要寫乙個查詢語句,...

乙個簡單的路徑查詢問題

這是網上的haskell99題中第81題 path from one node to another one write a function that,given two nodes a and b in a graph,returns all the acyclic paths from a t...