1. 程式人生 > >mysql的一個聯合查詢列子

mysql的一個聯合查詢列子

一個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的欄位。
通過符合使用者習慣的列印方式print_r來列印$myrow,結果如下:
Array (
    [0] => 1
    [pid] => 1
    [1] => A01
    [ptype] => A01
    [2] => 1
    [pparent] => 1
    [3] => 1
    [id] => 1
    [4] => 男裝
    [cname] => 男裝
……
)