您的位置:首页 > 数据库 > MySQL

mysql的一个联合查询列子

2006-10-26 21:16 459 查看
一个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] => 男装
……
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: